java反射,ReflectUtils,javareflectutils

來源:互聯網
上載者:User

java反射,ReflectUtils,javareflectutils

  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     }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.