通過反射實現get和set方法


/* setter方法 o:要操作類的對象 args:屬性名 attributeValue:屬性值 */
    public static void setXxx(Object o,String args,Object attributeValue){ Class cls = o.getClass(); //判斷該屬性是否存在
        Field field = null; try { field = cls.getDeclaredField(args); if(field == null){ field = cls.getField(args); } if(field == null){ return; } } catch (NoSuchFieldException e) { e.printStackTrace(); } String fieldName = "set"+args.substring(0,1).toUpperCase()+(args.length()>1?args.substring(1):""); Method method = null; try { method = cls.getMethod(fieldName,attributeValue.getClass()); method.invoke(o,attributeValue); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
 /* getter方法 o:要操作類的對象 args:屬性名 */
    public static <T> T getXxx(T o,String args) throws NoSuchFieldException { Class cls = o.getClass(); //判斷該屬性是否存在
        Field field = field = cls.getDeclaredField(args); if(field == null){ field = cls.getField(args); } if(field == null){ return null; } String fieldName = "get"+args.substring(0,1).toUpperCase()+(args.length()>1?args.substring(1):""); Method method = null; try { method = cls.getMethod(fieldName); return (T)method.invoke(o); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM