1、创建工具类
package com.base.reflect;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//@Slf4j
public class BeansFieldUtils {
public static Map<String, Object> getObjectValue(Object object, Set<String> set) {
Map<String, Object> map = new HashMap<>();
Class<?> clz = object.getClass();
Field[] fields = clz.getDeclaredFields();
try {
for (Field field : fields) {
if (!set.contains(field.getName())) {
continue;
}
Object val = FieldUtils.readField(field, object, true);
map.put(field.getName(), val);
}
} catch (Exception e) {
// log.error("获取属性异常:{}", e);
}
return map;
}
public static Map<String, Object> getObjectValue(Object object) {
Map<String, Object> map = new HashMap<>();
Class<?> clz = object.getClass();
Field[] fields = clz.getDeclaredFields();
try {
for (Field field : fields) {
Object val = FieldUtils.readField(field, object, true);
map.put(field.getName(), val);
}
} catch (Exception e) {
// log.error("获取属性异常:{}", e);
}
return map;
}
public static void main(String[] args) {
UserInfo user = new UserInfo();
Student student = new Student();
Map userMap = getObjectValue(user);
Map studentMap = getObjectValue(student);
System.out.print("user:");
userMap.forEach((key, value) -> {
System.out.print(key + "=" + value + ";");
});
System.out.println();
System.out.print("student:");
studentMap.forEach((key, value) -> {
System.out.print(key + "=" + value + ";");
});
System.out.println();
}
}
2、Student类
package com.base.reflect;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name = "张明";
private Integer age = 15;
private Integer height = 181;
}
3、UserInfo类
package com.base.reflect;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private String name = "张三 ";
private String gender = "男";
private Integer age = 20;
}
4、打印输出
user:gender=男;name=张三 ;age=20;
student:name=张明;age=15;height=181;