博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
反射工具类
阅读量:4646 次
发布时间:2019-06-09

本文共 12229 字,大约阅读时间需要 40 分钟。

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
map = cmdObj.getParams(); for (Map.Entry
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
map = new HashMap
(); 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
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
map = new HashMap
(); 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
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
,Object> defaultValueMap = new HashMap
,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;	}}

  

转载于:https://www.cnblogs.com/JAYIT/p/9300955.html

你可能感兴趣的文章
Fabric远程自动化使用说明
查看>>
linux php命令安装
查看>>
热身赛应该做什么?
查看>>
动手实现读写锁
查看>>
HNOI2010 合唱队
查看>>
或、异或
查看>>
智商的比拼——思维题思考指南
查看>>
MoveWindow() SetWindowPos()的区别与联系
查看>>
pthread_cond_signal惊群现象
查看>>
PHP CURL CURLOPT参数说明(curl_setopt)
查看>>
js深入(三)作用域链与闭包
查看>>
ubuntu sudo update与upgrade的作用及区别
查看>>
js创建javaMap
查看>>
LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
查看>>
20155334 曹翔 《网络对抗》逆向及Bof基础
查看>>
Block 的基本用法
查看>>
sklearn学习笔记之简单线性回归
查看>>
Git 配置
查看>>
测试代码发布到博客效果(使用word发布)
查看>>
LoadRunner-Linux监控工具nmon使用
查看>>