根據屬性拿到get和set方法
阿新 • • 發佈:2017-08-01
rop start getname code color readme stat end 沒有
public static void method(Object obj) { try { Class<? extends Object> clazz = obj.getClass(); Field[] fields = obj.getClass().getDeclaredFields();// 獲得屬性 for (Field field : fields) { System.out.println(field.getName());try { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); // getMethod Method getMethod = pd.getReadMethod();// 獲得get方法 if (getMethod != null) { System.out.println("getMethod = " + getMethod.getName()); // Object o = getMethod.invoke(obj);//執行get方法返回一個Object } // setMethod Method setMethod = pd.getWriteMethod(); if (setMethod != null) { System.out.println("setMethod = " + setMethod.getName()); } System.out.println("字段"+field.getName() + ": has get and set method"); } catch (Exception e) { // 字段沒有get或set方法時拋出異常 continue;<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span> }</span>
方式二:
/** * @author huangjunyan * 函數將oldObject的值復制到newObject當中,用於批量復制 * */ public static void copyProperties(Object oldObject,Object newObject) throws Exception{ //獲取oldObject的get方法域,遍歷方法域對比是否在newobject中存在set方法, //若存在則執行newObject對應的set方法 if(oldObject==null||newObject==null)return; Method[]oldObjectMethods = oldObject.getClass().getMethods(); Method[]newObjectMethods = newObject.getClass().getMethods(); Map<String,Method>setMethodMap = new HashMap<String,Method>(); //獲取所有set方法 for(int j=0;j<newObjectMethods.length;j++){ Method newObjectMethod = newObjectMethods[j]; if(newObjectMethod.getName().startsWith("set")){ setMethodMap.put(newObjectMethod.getName(), newObjectMethod); }; } for(int i=0;i<oldObjectMethods.length;i++){ Method oldObjectMethod = oldObjectMethods[i]; if(oldObjectMethod.getName().startsWith("get")){ String setName = oldObjectMethod.getName().replace("get", "set"); if(setMethodMap.containsKey(setName)){ Method newObjectMethod =setMethodMap.get(setName); //執行get,獲取需要設置的值 Object object=oldObjectMethod.invoke(oldObject, new Object[0]); Object[]objectArray; if(object==null){ objectArray = new Object[1]; objectArray[0] = null; }else{ objectArray = new Object[1]; objectArray[0] =convertType(newObjectMethod,object); } newObjectMethod.invoke(newObject, objectArray); } } } }
根據屬性拿到get和set方法