zoukankan      html  css  js  c++  java
  • java 反射之获取泛型对象的所有字段与对应的值(包括父类的)

    上代码:

    public static void main(String[] args) throws IntrospectionException {
            SysUser obj = new SysUser();
            obj.setId(1L);
            obj.setUserName("测试");
            obj.setCreatedDate(LocalDateTime.now());
    
            Class<?> clazz = SysUser.class;
            Field[] tableFields = clazz.getDeclaredFields();
            Class<?> superClazz = clazz.getSuperclass();
            if (superClazz.equals(Object.class)) {
                System.out.println("没有父类");
            } else {
                Field[] tableSuperFields = superClazz.getDeclaredFields();
                Field[] superFields = new Field[tableFields.length + tableSuperFields.length];
                System.arraycopy(tableFields, 0, superFields, 0, tableFields.length);
                System.arraycopy(tableSuperFields, 0, superFields, tableFields.length, tableSuperFields.length);
                Field[] allFields = getSuperClassFields(superFields, superClazz);
                for (int i = 0; i < allFields.length; i++) {
                    PropertyDescriptor pd = new PropertyDescriptor(allFields[i].getName(), clazz);
                    Method getMethod = pd.getReadMethod();//获得get方法
                    Object fieldValue = ReflectionUtils.invokeMethod(getMethod, obj);
                    if(fieldValue == null){
                        continue;
                    }
    
                    System.out.println(allFields[i].getName() + "的值:" +  fieldValue.toString());
                }
            }
        }
    
    //获取父类的所有字段
    private static Field[] getSuperClassFields(Field[] tableFields, Class<?> clazz) { Class<?> superClazz = clazz.getSuperclass(); if (superClazz.equals(Object.class)) { return tableFields; } Field[] tableSuperFields = superClazz.getDeclaredFields(); Field[] c = new Field[tableFields.length + tableSuperFields.length]; System.arraycopy(tableFields, 0, c, 0, tableFields.length); System.arraycopy(tableSuperFields, 0, c, tableFields.length, tableSuperFields.length); getSuperClassFields(c, superClazz); return c; }

    输出结果:

  • 相关阅读:
    LaZagne — 一键抓取目标机器上的所有明文密码,todo,自己手动试试效果
    jsch文件复制(拷贝)
    使用Apache commons-pool2实现高效的FTPClient连接池的方法
    室内定位会议和期刊(2020-2021)
    Axure RP 9.0 Team Edition
    新电脑 windows 10 登录 执行此操作需要Internet
    maven配置,以及项目 Dependency xxxx not found 解决过程
    MySQL 下载网站
    Tomcat8.5和Tomcat9安装SSL证书的教程
    Python id() 函数
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/10406875.html
Copyright © 2011-2022 走看看