查阅资料遇到一个javaBean转为map的方法,在此记录一下:
public static Map javaBean2Map(Object bean) throws IllegalAccessException {
Map result = new HashMap<>();
Class> sourceClass = bean.getClass();
//拿到所有的字段,不包括继承的字段
Field[] sourceFiled = sourceClass.getDeclaredFields();
for (Field field : sourceFiled) {
field.setAccessible(true);
//设置可访问,不然拿不到private
FieldName fieldName = field.getAnnotation(FieldName.class);
if (fieldName == null) {
result.put(field.getName(), field.get(bean));
} else {
if (fieldName.Ignore()) continue;
result.put(fieldName.value(), field.get(bean));
}
}
return result;
}
代码中的FieldName是新建的类:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface FieldName {
String value() default "";
boolean Ignore() default false;
}
测试用例:
public static void main(String[] args) throws IllegalAccessException {
Employee employee = new Employee();
employee.setBirthDay(new Date());
employee.setEmplId("1000");
employee.setEmplName("信息技术部");
employee.setEmplName("张三");
Map map= javaBean2Map(employee);
Set keySet = map.keySet();
System.out.println("employee转为map后的输出结果:");
for (String key:keySet
) {
System.out.println("key:"+key+" value:"+map.get(key));
}
}
测试结果:
转载于:https://www.cnblogs.com/obonika/p/10221253.html
点赞
收藏
分享
文章举报
aijieshi3669
发布了0 篇原创文章 · 获赞 0 · 访问量 178
私信
关注