首页 > 其他 > 详细

通过反射实现get和set方法

时间:2019-04-27 12:42:37      阅读:357      评论:0      收藏:0      [点我收藏+]
/*
        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;
    }

 

通过反射实现get和set方法

原文:https://www.cnblogs.com/du001011/p/10778334.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!