zoukankan      html  css  js  c++  java
  • 通过反射实现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;
        }
  • 相关阅读:
    Asp.net2.0页面执行顺序
    [转帖]常用的SQL语句
    [转帖]黑客技术经典问题FAQ
    面试的一些心得
    较全的正则表达式
    很好的创业建议
    [转帖]如何让菜单项与工具栏按钮对应
    源码下载网站
    [转帖]一段测试代码
    GOF设计模式趣解(23种设计模式) <转自百度空间>
  • 原文地址:https://www.cnblogs.com/du001011/p/10778334.html
Copyright © 2011-2022 走看看