java反射,ReflectUtils

  1 public class ReflectUtils {
  2     /** 
  3      * 通过构造函数实例化对象  
  4      * @param className       类的全路径名称    
  5      * @param parameterTypes  参数类型 
  6      * @param initargs        参数值 
  7      * @return 
  8      */    
  9     @SuppressWarnings("rawtypes")  
 10     public static Object constructorNewInstance(String className,Class [] parameterTypes,Object[] initargs) {   
 11         try {  
 12             Constructor<?> constructor = (Constructor<?>) Class  
 13                     .forName(className).getDeclaredConstructor(parameterTypes);                    
 14             constructor.setAccessible(true);  
 15             return constructor.newInstance(initargs);  
 16         } catch (Exception ex) {  
 17             throw new RuntimeException();  
 18         }  
 19   
 20     }  
 21   
 22       
 23     /** 
 24      * 获取字段值 
 25      * @param propertyName 属性名 
 26      * @param object       实例对象 
 27      * @return          字段值 
 28      */  
 29     public static Object getProperty(String propertyName, Object object) {  
 30         try {  
 31               
 32             PropertyDescriptor pd = new PropertyDescriptor(propertyName,object.getClass());  
 33             Method method = pd.getReadMethod();  
 34             return method.invoke(object);  
 35         } catch (Exception ex) {  
 36             throw new RuntimeException();  
 37         }  
 38     }  
 39       
 40     /** 
 41      * 通过BeanUtils工具包获取反射获取字段值,注意此值是以字符串形式存在的,它支持属性连缀操作:如,.对象.属性 
 42      * @param propertyName 属性名 
 43      * @param object       实例对象 
 44      * @return          字段值 
 45      */    
 46     public static Object getBeanInfoProperty(String propertyName, Object object) {  
 47         try {             
 48             return BeanUtils.getProperty(object, propertyName);  
 49         } catch (Exception ex) {  
 50             throw new RuntimeException();  
 51         }  
 52     }  
 53       
 54     /** 
 55      * 通过BeanUtils工具包获取反射获取字段值,注意此值是以字符串形式存在的 
 56      * @param object       实例对象 
 57      * @param propertyName 属性名 
 58      * @param value        字段值 
 59      * @return           
 60      */    
 61     public static void setBeanInfoProperty(Object object,String propertyName,String value) {  
 62         try {             
 63             BeanUtils.setProperty(object, propertyName,value);  
 64         } catch (Exception ex) {  
 65             throw new RuntimeException();  
 66         }  
 67     }  
 68       
 69     /** 
 70      * 通过BeanUtils工具包获取反射获取字段值,注意此值是以对象属性的实际类型 
 71      * @param propertyName 属性名 
 72      * @param object       实例对象 
 73      * @return          字段值 
 74      */   
 75     public static Object getPropertyUtilByName(String propertyName, Object object) {  
 76         try {             
 77             return PropertyUtils.getProperty(object, propertyName);  
 78         } catch (Exception ex) {  
 79             throw new RuntimeException();  
 80         }  
 81     }  
 82       
 83     /** 
 84      * 通过BeanUtils工具包获取反射获取字段值,注意此值是以对象属性的实际类型,这是PropertyUtils与BeanUtils的根本区别 
 85      * @param object       实例对象 
 86      * @param propertyName 属性名 
 87      * @param value        字段值 
 88      * @return           
 89      */   
 90     public static void setPropertyUtilByName(Object object,String propertyName,Object value) {  
 91         try {             
 92             PropertyUtils.setProperty(object, propertyName,value);  
 93         } catch (Exception ex) {  
 94             throw new RuntimeException();  
 95         }  
 96     }  
 97       
 98     /** 
 99      * 设置字段值     
100      * @param obj          实例对象 
101      * @param propertyName 属性名 
102      * @param value        新的字段值 
103      * @return           
104      */ 
105     public static void setProperties(Object object, String propertyName,Object value) throws IntrospectionException,  
106             IllegalAccessException, InvocationTargetException {  
107         PropertyDescriptor pd = new PropertyDescriptor(propertyName,object.getClass());  
108         Method methodSet = pd.getWriteMethod();  
109         methodSet.invoke(object,value);  
110     }  
111       
112       
113     /** 
114      * 设置字段值 
115      * @param className        类的全路径名称 
116      * @param methodName       调用方法名 
117      * @param parameterTypes   参数类型 
118      * @param values           参数值 
119      * @param object           实例对象 
120      * @return           
121      */  
122     @SuppressWarnings("rawtypes")  
123     public static Object methodInvoke(String className,String methodName,Class [] parameterTypes,Object [] values,Object object) {  
124         try {  
125             Method method = Class.forName(className).getDeclaredMethod(methodName,parameterTypes);  
126             method.setAccessible(true);  
127             return method.invoke(object,values);  
128         } catch (Exception ex) {  
129             throw new RuntimeException();  
130         }  
131     }    
132   
133     /** 
134      * @param <T> 具体对象 
135      * @param fileds  要进行比较Bean对象的属性值集合(以属性值为key,属性注释为value,集合从数据库中取出) 
136      * @param oldBean  源对象 
137      * @param newBean  新对象 
138      * @return 返回二个Bean对象属性值的异同 
139      */  
140     @SuppressWarnings("unused")
141     public static <T> String compareBeanValue(Map<String,String> fileds,T oldBean,T newBean){  
142           
143         StringBuilder compares = new StringBuilder();  
144         String propertyName = null;       
145         Object oldPropertyValue = null;  
146         Object newPropertyValue = null;  
147           
148         StringBuilder descrips = new StringBuilder();                 
149         for(Map.Entry<String, String> entity : fileds.entrySet()){  
150             propertyName = entity.getKey().toLowerCase();  
151             oldPropertyValue = getProperty(propertyName, oldBean);  
152             newPropertyValue = getProperty(propertyName, newBean);            
153                               
154             if(null == oldPropertyValue && null == newPropertyValue){  
155                 continue;  
156             }             
157             if("".equals(oldPropertyValue) && "".equals(newPropertyValue)){  
158                 continue;  
159             }             
160             if(null == oldPropertyValue){  
161                 oldPropertyValue = "";  
162             }             
163             if(null == newPropertyValue){  
164                 newPropertyValue = "";  
165             }             
166               
167             if(oldPropertyValue.equals(newPropertyValue)){            
168                 continue;  
169             }  
170             compares.append("字段注释: ").append(entity.getValue()).append("】").append("原属性值\"");  
171             if(StringUtils.isEmpty(oldPropertyValue+"")){  
172                 oldPropertyValue = " ";  
173             }  
174             compares.append(oldPropertyValue).append("\"现属性值\"");  
175             if(StringUtils.isEmpty(newPropertyValue+"")){  
176                 newPropertyValue = " ";  
177             }  
178             compares.append(newPropertyValue).append("\";");              
179         }         
180         return compares.toString();  
181     }
182  
183     
184     /*** 
185      * 暴力反射获取字段值 
186      * @param obj       实例对象 
187      * @param fieldName 属性名 
188      * @return          属性值 
189      */
190     public static Object getFieldValue(Object obj, String fieldName){
191         if(obj == null){  
192             return null ;  
193         }    
194         Field targetField = getTargetField(obj.getClass(), fieldName);  
195           
196         try {  
197             return FieldUtils.readField(targetField, obj, true ) ;  
198         } catch (IllegalAccessException e) {  
199             e.printStackTrace();  
200         }   
201         return null ;
202     }
203     
204     public static Field getTargetField(Class<?> targetClass, String fieldName) {  
205         Field field = null;  
206   
207         try {  
208             if (targetClass == null) {  
209                 return field;  
210             }  
211   
212             if (Object.class.equals(targetClass)) {  
213                 return field;  
214             }  
215   
216             field = FieldUtils.getDeclaredField(targetClass, fieldName, true);  
217             if (field == null) {  
218                 field = getTargetField(targetClass.getSuperclass(), fieldName);  
219             }  
220         } catch (Exception e) {  
221         }  
222   
223         return field;  
224     }
225     
226     /** 
227      * 设置字段值 
228      * @param propertyName 字段名 
229      * @param obj          实例对象 
230      * @param value        新的字段值 
231      * @return           
232      */
233     public static void setFieldValue(Object obj , String fieldName , Object value ){  
234         if(null == obj){return;}  
235         Field targetField = getTargetField(obj.getClass(), fieldName);    
236         try {  
237              FieldUtils.writeField(targetField, obj, value) ;  
238         } catch (IllegalAccessException e) {  
239             e.printStackTrace();  
240         }   
241     }

 

转载于:https://www.cnblogs.com/tianrongyao/p/reflectutils.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值