Java 反射获取对象里的值

  最近在负责邮件服务,里面会涉及到很多Email模板,这里我使用到了java的模板引擎:jetbrick-template,需要使用Map集合一个个往里面设置值,然后调用模板方法,进行替换。实体类一个个往Map中设置值,感觉非常麻烦,工作效率极低,此时想到了使用Java中的反射获得实体类中的值,工具类如下

  java 模板引擎点我直达

工具类

package com.ybchen.springbootohmyemail.convert;

import com.sun.tools.javac.code.Attribute;
import com.ybchen.springbootohmyemail.entity.EmailData;

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

/**
 * @ClassName:ReplaceEmailTemplate
 * @Description:邮件模板转换工具
 * @Author:chenyb
 * @Date:2020/11/30 6:52 下午
 * @Versiion:1.0
 */
public class ReplaceEmailTemplate {
    /**
     * 实体类转Map
     * @param clazz 类
     * @param obj 实体类
     * @param <T> 实体类
     * @return
     */
    public static<T> Map<String,Object> replaceContext(Class<?> clazz,T obj) {
        Map<String,Object> map=new HashMap<String,Object>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field f:declaredFields){
            try {
                //打开可见性,要不然获取不到值
                f.setAccessible(true);
                map.put(f.getName(),f.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }finally {
                //关闭可见性
                f.setAccessible(false);
            }
        }
        return map;
    }
}

调用

EmailData emailData = new EmailData("ybchen", "199999999", "www.baidu.com");
Map<String, Object> map = ReplaceEmailTemplate.replaceContext(EmailData.class,emailData);
package com.ybchen.springbootohmyemail.entity;

import java.io.Serializable;

/**
 * @ClassName:EmailData
 * @Description:TODO
 * @Author:chenyb
 * @Date:2020/11/30 6:56 下午
 * @Versiion:1.0
 */
public class EmailData implements Serializable {
    private String username;
    private String email;
    private String url;

    public EmailData() {
    }

    public EmailData(String username, String email, String url) {
        this.username = username;
        this.email = email;
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "EmailData{" +
                "username='" + username + '\'' +
                ", email='" + email + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}

 

posted @ 2020-11-30 19:26  陈彦斌  阅读(1564)  评论(0编辑  收藏  举报