java:获取对象/实体类的全部字段

  • Post author:
  • Post category:java


Number 1

public <T> T compareObjUtil(CompareSettlementDto t1) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Field[] objFields = t1.getClass().getDeclaredFields();//字段信息集合
        Field.setAccessible(objFields, true);
        if (objFields != null && objFields.length > 0) {
            for (int i = 0; i < objFields.length; i++) {
                String objName = objFields[i].getName();//字段名称
                Object promptValue = objFields[i].get(t1);//字段值
                String valueType = objFields[i].getType().toString();//字段类型

            }
        }
        return (T) map;
    }

Number 2

public static Map<String, Object> entityToMap(Object bean) throws Exception {
        Class type = bean.getClass();
        Map<String,Object> returnMap = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();//name
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);//value
                String typeName = descriptor.getPropertyType().getName();//type
            }
        }
        return returnMap;
    }

Number3:只获取字段名,包括继承类

public static void main(String[] args) {
        Class c = SystemUserId.class;
        List<Field> fields = new ArrayList<>();
        while (c != null){
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
            c = c.getSuperclass();
        }
        fields.forEach(System.out::println);
    }



版权声明:本文为weixin_55450918原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。