zoukankan      html  css  js  c++  java
  • java通过反射获取Java对象属性值

    说明:

      作为反射工具类,通过对象和属性的名字获取对象属性的值,如果在当前对象属性没有找到,依次向上收集所有父类的属

    性,直到找到属性值,没有找到返回null;

    代码:

      1.classUtil

      

    package com.example.demo.utill;
    
    import java.lang.reflect.Field;
    
    /**
     * description: TODO
     * date: 2020/3/24 0024 下午 21:32
     *
     * @author : Administrator
     * @since : 1.0
     **/
    public class ClassUtil {
    
        public static Object getPropertyValue(Object obj, String propertyName) throws IllegalAccessException {
            Class<?> Clazz = obj.getClass();
            Field field;
            if ((field = getField(Clazz, propertyName)) == null)
                return null;
            field.setAccessible(true);
            return field.get(obj);
        }
    
        public static Field getField(Class<?> clazz, String propertyName) {
            if (clazz == null)
                return null;
            try {
                return clazz.getDeclaredField(propertyName);
            } catch (NoSuchFieldException e) {
                return getField(clazz.getSuperclass(), propertyName);
            }
        }
    }

      2.测试类和接口

    package com.example.demo.utill;
    
    /**
     * description: TODO
     * date: 2020/3/24 0024 下午 21:50
     *
     * @author : Administrator
     * @since : 1.0
     **/
    public class Person {
        private String age;
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    }
    package com.example.demo.utill;
    
    /**
     * description: TODO
     * date: 2020/3/24 0024 下午 21:42
     *
     * @author : Administrator
     * @since : 1.0
     **/
    public class User  extends Person{
        private String name ;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    3.测试

    package com.example.demo.utill;
    
    /**
     * description: TODO
     * date: 2020/3/24 0024 下午 21:41
     *
     * @author : Administrator
     * @since : 1.0
     **/
    public class Test {
        public static void main(String[] args) throws IllegalAccessException {
            User u = new User();
            u.setName("张三");
            u.setAge("20");
            Object o = ClassUtil.getPropertyValue(u,"ag1e");
            System.out.println(o);
        }
    }
    // outPut:null
  • 相关阅读:
    获取某表所有列名和字段类型
    C++ 长指针与指针的区别
    C# WinForm 控件光标
    不错的UML建模工具StarUML
    给控件做数字签名之一:将控件打包为Web发布包(转)
    MsComm控件注册失败
    微软发布Microsoft图表控件
    C与C++中的宏
    WinForm DataGridView 显示行号
    C#ToString格式大全
  • 原文地址:https://www.cnblogs.com/jonrain0625/p/12562480.html
Copyright © 2011-2022 走看看