历遍没一个属性,获取里面的值,
如果属性用private 修饰,可能读不出来
package com.ibeetl.admin.core.util; import com.fasterxml.jackson.annotation.JsonProperty; import java.lang.reflect.Field; public class ObjectUtil { public static Object getFieldValueFromObject(Object object, String targetFieldName) throws Exception { // 获取该对象的Class Class objClass = object.getClass(); // 获取所有的属性数组 Field[] fields = objClass.getDeclaredFields(); for (Field field : fields) { // 属性名称 String currentFieldName = ""; // 获取属性上面的注解 import com.fasterxml.jackson.annotation.JsonProperty; /* * 举例: * @JsonProperty("di_ren_jie") * private String diRenJie; */ boolean has_JsonProperty = field.isAnnotationPresent(JsonProperty.class); if (has_JsonProperty) { currentFieldName = field.getAnnotation(JsonProperty.class).value(); } else { currentFieldName = field.getName(); } if (currentFieldName.equals(targetFieldName)) { // 通过反射拿到该属性在此对象中的值(也可能是个对象) return field.get(object); } } return null; } static class User { String name; String age; User(String name, String age) { this.name = name; this.age = age; } } public static void main(String[] args) throws Exception { User user = new User("zhangsan", "11"); System.out.println(getFieldValueFromObject(user, "name")); } }
运行结果为