注意
- getter和setter方法的命名要规范
- PropertyDescriptor(jdk1.8):要求setter返回值为void
- lombok的@Accessors(chain = true):链式调用注解,setter方法返回对象本身
Main
public class Main { public static void main(String[] args) throws Exception { Student xcrj = new Student(); xcrj.setName("xcrj"); MapnamevalueMap = getObjFieldNamevalue(xcrj); } public static Map getObjFieldNamevalue(Object obj) throws Exception { Class clazz = obj.getClass(); Map map = new HashMap<>(); // getDeclaredFields Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { String fieldName = field.getName(); // PropertyDescriptor PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz); // getMethod Method getMethod = pd.getReadMethod(); Object value = getMethod.invoke(obj); map.put(fieldName, value); } return map; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)