反射工具类
Posted jayit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射工具类相关的知识,希望对你有一定的参考价值。
public class ReflectUtil { private final static Logger log = Logger.getLogger(ReflectUtil.class); public static void setFieldValue(Object target, String fname , Object fvalue, Class<?> ftype){ if((null == target) || StringHelper.isBlank(fname) || ((null != fvalue) && !ftype.isPrimitive() && (!ftype.isAssignableFrom(fvalue.getClass())))){ log.error("setFieldValue. parameters is error: target[" + target + "];fname=" + fname + ";fvalue=" + fvalue + ";ftype=" + ftype + ";fvaluetype="+fvalue.getClass()); return; } Class<?> clazz = target.getClass(); try{ Method method = clazz.getDeclaredMethod("set" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), new Class[] { ftype }); if(!Modifier.isPublic(method.getModifiers())){ method.setAccessible(true); } method.invoke(target, fvalue); }catch (Exception ex1) { try { Field field = clazz.getDeclaredField(fname); if(!Modifier.isPublic(field.getModifiers())){ field.setAccessible(true); } field.set(target, fvalue); }catch (Exception ex2){ log.error("setFieldValue. setmethod is error: target=" + target.getClass() + ";" + fname + "=" + fvalue + ";ftype=" + ftype + ";fvaluetype="+fvalue.getClass()); log.error(ex2.getMessage(),ex2); } } } public static Object getFieldValue(Object target, String fname) { if (null == target || StringHelper.isBlank(fname)) { log.error("getFieldValue. parameters is error: target=" + target+ ";fname=" + fname); return null; } boolean exCatched = false; Class<?> clazz = target.getClass(); try { Method method = clazz.getDeclaredMethod("get" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1)); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } return method.invoke(target); }catch (NoSuchMethodException e) { exCatched = true; } catch (InvocationTargetException e) { exCatched = true; }catch (IllegalAccessException e) { exCatched = true; } if (exCatched) { try { Field field = clazz.getDeclaredField(fname); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } return field.get(target); } catch (Exception ex) { log.error("getFieldValue. " + fname + " cannot get value: "+ex.getMessage()); } } return null; } }
public class ClassHelper{ private final static Logger log = Logger.getLogger(ClassHelper.class); public static void formatCommandObj(CommandObj cmdObj,Object target){ Class<?> clazz = target.getClass(); Field[] selffields = clazz.getDeclaredFields(); Field[] supfields = clazz.getSuperclass().getDeclaredFields(); Field[] fields= new Field[selffields.length+supfields.length]; System.arraycopy(selffields, 0, fields, 0, selffields.length); System.arraycopy(supfields, 0, fields, selffields.length, supfields.length); String fname = null; Object fvalue = null, mvalue = null; Class<?> ftype = null; Map<String,String> map = cmdObj.getParams(); for (Map.Entry<String, String> o : map.entrySet()) { fname = o.getKey(); fvalue = o.getValue(); ftype = null; for(Field f : fields) { if(f.getName().equals(fname)){ ftype = f.getType(); if(StringHelper.isBlank(String.valueOf(fvalue)) && ftype.isPrimitive()){ fvalue = getPrimitiveDefaultValue(ftype); } try{ mvalue = cast(ftype ,fvalue, null, 0); }catch(BtirException ex){ log.error(ex.getMessage(), ex); } ReflectUtil.setFieldValue(target , fname, mvalue, ftype); break; } } } } public static void formatResultSet(ResultSet rs,Object target){ Class<?> clazz = target.getClass(); Field[] fields = clazz.getDeclaredFields(); Column col = null; String fname = null; Object fvalue = null; Class<?> ftype = null; boolean isMatch = false; for (Field f : fields) { col = f.getAnnotation(Column.class); if(null != col && StringHelper.isNotBlank(col.name())){ fname = f.getName(); ftype = f.getType(); try{ fvalue = rs.getObject(col.name()); isMatch = true; }catch(SQLException ex){ isMatch = false; } if(isMatch){ if(StringHelper.isBlank(String.valueOf(fvalue)) && ftype.isPrimitive()){ fvalue = getPrimitiveDefaultValue(ftype); } ReflectUtil.setFieldValue(target , fname, fvalue, ftype); }else{ log.warn("Column ‘" + col.name() + "‘ not found."); } } } } public static void encodeObject(ByteBuffer buffer, Object target){ Class<?> clazz = target.getClass(); Field[] fields = clazz.getDeclaredFields(); Field f = null; Column col = null; Map<Integer,Field> map = new HashMap<Integer,Field>(); for (Field field : fields) { col = field.getAnnotation(Column.class); if(null != col && col.seq() > 0){ map.put(col.seq(), field); } } String fname = null; Object fvalue = null; Class<?> ftype = null; for (Map.Entry<Integer, Field> o : map.entrySet()) { f = o.getValue(); fname = f.getName(); fvalue = ReflectUtil.getFieldValue(target, fname); ftype = f.getType(); try{ cast(ftype, fvalue, buffer, 1); }catch(BtirException ex){ log.error(ex.getMessage(), ex); } } } public static void decodeObject(ByteBuffer buffer,Object target) throws BtirException{ Class<?> clazz = target.getClass(); Field[] fields = clazz.getDeclaredFields(); Field f = null; Column col = null; Map<Integer,Field> map = new HashMap<Integer,Field>(); for (Field field : fields) { col = field.getAnnotation(Column.class); if(null != col && col.seq() > 0){ map.put(col.seq(), field); } } String fname = null; Object fvalue = null; Class<?> ftype = null; for (Map.Entry<Integer, Field> o : map.entrySet()) { f = o.getValue(); fname = f.getName(); ftype = f.getType(); fvalue = cast(ftype, null, buffer, 2); ReflectUtil.setFieldValue(target, fname, fvalue, ftype); } } public static String formatObjectToString(Object target){ Field[] fields = target.getClass().getDeclaredFields(); StringBuilder sb = new StringBuilder(""); String fname = null; Object fvalue = null; for(Field f : fields) { fname = f.getName(); fvalue = ReflectUtil.getFieldValue(target, fname); sb.append(fname + "=" + fvalue +";"); } return sb.toString(); } private static Object cast(Class<?> disttype, Object orgvalue, ByteBuffer buffer, int castType)throws BtirException{ Object distvalue = null; String disttypename = disttype.getSimpleName().toLowerCase(); //castType??0 ?????????1 ????2 ???? if(null != orgvalue && 0 == castType && orgvalue.getClass().isAssignableFrom(disttype)){ return orgvalue; } int o_iRetval = 0; if(disttype.isAssignableFrom(String.class)){ if(0 == castType){ distvalue = (String)orgvalue; }else if(1 == castType){ EncodeUtil.encodeShortLen_Str(buffer, (String)orgvalue); }else if(2 == castType){ distvalue = EncodeUtil.decodeShortLen_Str(buffer); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("int") != -1){ if(0 == castType){ distvalue = StringHelper.objectToInteger(orgvalue); }else if(1 == castType){ buffer.putInt(StringHelper.objectToInteger(orgvalue)); }else if(2 == castType){ distvalue = buffer.getInt(); }else{ o_iRetval = -1; } }else if(disttype.isAssignableFrom(Timestamp.class)){ if(0 == castType){ distvalue = StringHelper.objectToTimestamp(orgvalue); }else if(1 == castType){ EncodeUtil.encodeTimestampByLong(buffer , StringHelper.objectToTimestamp(orgvalue)); }else if(2 == castType){ distvalue = EncodeUtil.decodeTimestampByLong(buffer); }else{ o_iRetval = -1; } }else if(disttype.isAssignableFrom(Date.class)){ if(0 == castType){ distvalue = StringHelper.objectToDate(orgvalue); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("byte") != -1){ if(0 == castType){ distvalue = StringHelper.objectToByte(orgvalue); }else if(1 == castType){ buffer.put(StringHelper.objectToByte(orgvalue)); }else if(2 == castType){ distvalue = buffer.get(); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("short") != -1){ if(0 == castType){ distvalue = StringHelper.objectToShort(orgvalue); }else if(1 == castType){ buffer.putShort(StringHelper.objectToShort(orgvalue)); }else if(2 == castType){ distvalue = buffer.getShort(); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("float") != -1){ if(0 == castType){ distvalue = StringHelper.objectToFloat(orgvalue); }else if(1 == castType){ buffer.putFloat(StringHelper.objectToFloat(orgvalue)); }else if(2 == castType){ distvalue = buffer.getFloat(); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("long") != -1){ if(0 == castType){ distvalue = StringHelper.objectToLong(orgvalue); }else if(1 == castType){ buffer.putLong(StringHelper.objectToLong(orgvalue)); }else if(2 == castType){ distvalue = buffer.getLong(); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("double") != -1){ if(0 == castType){ o_iRetval = -1; }else if(1 == castType){ buffer.putDouble(StringHelper.objectToDouble(orgvalue)); }else if(2 == castType){ distvalue = buffer.getDouble(); }else{ distvalue = StringHelper.objectToDouble(orgvalue); } }else if(disttypename.indexOf("char") != -1){ if(0 == castType){ distvalue = (Character)orgvalue; }else if(1 == castType){ buffer.putChar((Character)orgvalue); }else if(2 == castType){ distvalue = buffer.getChar(); }else{ o_iRetval = -1; } }else if(disttypename.indexOf("boolean") != -1){ if(0 == castType){ distvalue = Boolean.parseBoolean((String)orgvalue); }else{ o_iRetval = -1; } }else if(disttype.isAssignableFrom(List.class)){ if(0 == castType){ distvalue = StringHelper.stringToList((String)orgvalue, ";"); }if(1 == castType){ EncodeUtil.encodeShortlen_StrList(buffer, StringHelper.stringToList((String)orgvalue, ";")); }else if(2 == castType){ distvalue = EncodeUtil.decodeShortLen_StrList(buffer); }else{ o_iRetval = -1; } }else if(disttype.isAssignableFrom(String[].class)){ if(0 == castType){ if(null !=orgvalue ) distvalue = ((String)orgvalue).split(";"); }else{ o_iRetval = -1; } }else if(disttype.isAssignableFrom(byte[].class)){ if(0 == castType){ distvalue = StringHelper.stringToBytes((String)orgvalue, ";"); }else if(1 == castType){ EncodeUtil.encodeByteLen_Bytes(buffer, (byte[])orgvalue); }else if(2 == castType){ distvalue = EncodeUtil.decodeByteLen_Bytes(buffer); }else{ o_iRetval = -1; } }else{ o_iRetval = -1; } if(-1 == o_iRetval){ log.error("cast type[" + castType + "] canot found?? distype=" + disttype + "; orgvalue=" + orgvalue + "; buffer=" + buffer); } return distvalue; } public static String createJsonStr(Object obj){ JsonConfig config=new JsonConfig(); config.setExcludes(new String[]{"command","node","sequence","sessionId","sourceIp"}); return JSONObject.fromObject(obj,config).toString(); } public static Object getPrimitiveDefaultValue(Class<?> type){ Map<Class<?>,Object> defaultValueMap = new HashMap<Class<?>,Object>(); defaultValueMap.put(byte.class, (byte)0); defaultValueMap.put(short.class, (short)0); defaultValueMap.put(int.class, 0); defaultValueMap.put(char.class, (char)‘0‘); defaultValueMap.put(long.class, 0l); defaultValueMap.put(float.class, 0.0f); defaultValueMap.put(double.class, 0.0d); defaultValueMap.put(boolean.class, false); return defaultValueMap.get(type); } }
public class Test{ @Column(seq=1,name = "tel") private String tel; @Column(seq=2,name = "business_code") private String businessCode; public Test(){ } public Test(ResultSet rs){ ClassHelper.formatResultSet(rs, this); } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getBusinessCode() { return businessCode; } public void setBusinessCode(String businessCode) { this.businessCode = businessCode; } }
以上是关于反射工具类的主要内容,如果未能解决你的问题,请参考以下文章