JavaBean转换成Map(配合注解实现属性过滤)

By | 2015年4月15日

1、首先编写一个注解类,用于标注在字段或者方法上,实现属性的过滤


package com.renyiwei.wydns.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
// 可以注解在方法或者字段上
@Target({ ElementType.FIELD, ElementType.METHOD })
public @interface ToMapIgnore {

boolean Value() default true;
}

2、编写工具类,实现对象到map的转化(该工具还没有完成读取get方法上的注解)


package com.renyiwei.wydns.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.renyiwei.wydns.annotation.ToMapIgnore;

public class CommonUtil {

public static Map toMap(Object bean) throws IllegalArgumentException, IllegalAccessException {
Map returnMap = new HashMap();
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
//获取该字段的注解
ToMapIgnore annotation = field.getAnnotation(ToMapIgnore.class);
//如果没有注解 或者 注解值为false 则获取该值存入返回的map中
if (annotation == null || !annotation.Value()) {
field.setAccessible(true);
returnMap.put(field.getName(), field.get(bean));
}
}
return returnMap;
}
}

3、实例:如果不想转化对象中的module属性,则在起字段上进行注解 @ToMapIgnore既可以


package com.renyiwei.wydns.domain;

import com.renyiwei.wydns.annotation.ToMapIgnore;

public class Server {

private Long id;
private String name;
private String apiurl;
private String username;
private String password;

//在这里进行注解
@ToMapIgnore
private Module module;

//省略get set方法
}

4、调用


Map serverMap = CommonUtil.toMap(product.getServer());