Java&Spring基础技术程序员

利用反射机制实现对象转Map集合

2018-06-02  本文已影响18人  雁归来兮

更多关于Java方面的文章,欢迎访问燕归来https://www.zhoutao123.com

前不久有个需求,实现对象转换为map,这里思考了一些,没有用别人的轮子,自己实现了这个需求,写了一个简单的工具类来做这个。

分析问题

问题主要有以下几点

解决问题

 /**
     * 处理方法,将get方法转换为属性名
     *
     * @param methodName
     * @return
     */
    public static String dealMethodName(String methodName) {
        StringBuilder stringBuilder = new StringBuilder();
        if (methodName.startsWith("get")) {
            stringBuilder.append(methodName.toLowerCase().charAt(3)).append(methodName.substring(4));
        } else if (methodName.startsWith("is")) {
            stringBuilder.append(methodName.toLowerCase().charAt(2)).append(methodName.substring(3));
        } else {
            return methodName;
        }
        return stringBuilder.toString();
    }
//作用于方法上,运行时保留
@Target(value={METHOD})
@Retention(RetentionPolicy.RUNTIME)
public  @interface NeedIterative {
    //参数没有作用
    String value() default "";
}

详细代码

首先实现POJO类,POJO类主要代码如下所示<span style="color:red;">set方法已省略,自行补充,People类也是</span>,

public class Student{
    private String name;
    private int age;
    private float height;
    private double weight;
    private char sex;
    private boolean allow;
    private People people;

    public Student(String name, int age, float height, double weight, char sex, boolean allow) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.weight = weight;
        this.sex = sex;
        this.allow = allow;
    }

    public String getName() { return name;}

    public int getAge() {  return age; }

    public float getHeight() { return height;}

    public double getWeight() {return weight;}

    public char getSex() {return sex;}

    public boolean isAllow() { return allow;}

    //此处添加了注解,说明此处返回的是一个POJO需要迭代处理
    @NeedIterative
    public People getPeople() { return new People("李亚伟",12); }

需要返回的对象POJO对象是People类的代码内容为

public class People{
    private String people;
    private int work;

    public People(String people, int work) {
        this.people = people;
        this.work = work;
    }

    public String getPeople() { return people; }

    public int getWork() { return work; }
}

反射返回对象

代码很见到,都是Class等常见的API,这里不做赘述。

    public static  Map toMap(Object obj) throws Exception {
        Class clazz = obj.getClass();
        //获得属性
        Field[] fields = obj.getClass().getDeclaredFields();
        HashMap hashMap = new HashMap(fields.length);
        for (Field field : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //获得get方法
            Method getMethod = pd.getReadMethod();
            //执行get方法返回一个Object
            Object exeValue = getMethod.invoke(obj);
            String key = dealMethodName(getMethod.getName());
            NeedIterative annotation = getMethod.getAnnotation(NeedIterative.class);
             //获取的注解不为空,那么说明此处返回的结果是对象,那么需要迭代处理
            if (annotation != null) {
                exeValue = toMap(exeValue);
            }
            hashMap.put(key, exeValue);
        }
        return hashMap;
    }

输出结果

由此可见,不管是基本数据类型,还是POJO类都能正常的转换。

断点数据类型查看:

image

sout输出效果如下:

{
        allow=true, 
        sex=m,
        name=周涛,
        weight=12.23,
        people={
                people=李亚伟, 
                work=12
                },
        age=23,
        height=12.12
}

更多关于Java方面的文章,欢迎访问燕归来https://www.zhoutao123.com

上一篇 下一篇

猜你喜欢

热点阅读