利用注解和反射,将Bean枚举字段的值填入相应的字段中,并转化为fastjson返回前台

需求:需要将枚举类型的字段例如enable(是否启用)转化为enable:1,enableName:是。这种形式返回给前台。

思路:在bean字段上加上枚举类型的注解,通过字段的值和枚举类反射获取枚举的key和value。

枚举注解:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 
 * <p>Title:用于bean字段枚举类型的注解</p>
 * <p>Description:</p>
 * @author zhy
 * @date 2019/02/27  
 * @version 1.0
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IEnum {
    String name() default "";//名称
    Class<?> clas();//枚举实体
    //byte defaultKey() default 0;//默认值
}

枚举接口:(这个也可以不要,预留以防万一要用到)

/**
 * 
 * <p>Title:</p>
 * <p>Description:</p>
 * @author zhy
 
 * @version 1.0
 */
public interface EnumBase {

    public String getName(Byte key);
}

枚举类

public enum OEnable implements EnumBase {
    TRUE(1, "启用"),FALSE(0, "停用");
    
    private Byte key;
    
    private String name;

    private OEnable(int key,String name) {
        this.key = (byte)key;
        this.name = name;
    }
    
    
    
    
    public Byte getKey() {
        return key;
    }




    public void setKey(Byte key) {
        this.key = key;
    }




    public String getName() {
        return name;
    }




    public void setName(String name) {
        this.name = name;
    }




    @Override
    public String getName(Byte key) {
        for (OEnable enable : values()) {
            if(key == null)
                return null;
            if (enable.getKey().equals(key)) {
                return enable.getName();
            }
        }
        return null;
    }

}

所有bean的基类,里面包含bean的基本属性。只有当结果集list里的类继承于这个类,我们才需要转换枚举值

import java.util.Date;


/**
 * 
 * <p>Title:所有bean基类</p>
 * <p>Description:</p>
 * @author zhy
 
 * @version 1.0
 */
public class BeanBase {
    
    protected Integer pkey;//主键
    
    protected Date createdTime;//创建时间
    
    protected Date updatedTime;//更新时间
    
    protected Integer rowVersion;//版本号

    public Integer getPkey() {
        return pkey;
    }

    public void setPkey(Integer pkey) {
        this.pkey = pkey;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    public Date getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(Date updatedTime) {
        this.updatedTime = updatedTime;
    }

    public Integer getRowVersion() {
        return rowVersion;
    }

    public void setRowVersion(Integer rowVersion) {
        this.rowVersion = rowVersion;
    }
    
    

}

Test类

public class Test extends BeanBase {
    
    public String name;
    
    @IEnum(clas = OEnable.class)
    public Byte enable;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Byte getEnable() {
        return enable;
    }

    public void setEnable(Byte enable) {
        this.enable = enable;
    }
    
    

}

bean转换工具类,通过反射获取字段信息,注解信息

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
public class BeanUtils {

    /**
     * 
     * <p>Title:bean字段转换类</p>
     * <p>Description:</p>
     * @author zhy
    
     * @version 1.0 
     * @param result
     * @return
     */
    public static List<Map<String,Object>> ListBeanToJson(List<? extends BeanBase> result) {
        List<Map<String,Object>> newResult = new ArrayList<Map<String,Object>>();
        for (BeanBase t : result) {
            Map<String, Object> tmap = beanToMap(t); 
            
            newResult.add(tmap);
        }
        return newResult;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> beanToMap(BeanBase t) {
        Map<String,Object> tmap = new HashMap<String,Object>();
        List<Field> fieldList = new ArrayList<>() ;
        Class<? extends BeanBase> class1 = t.getClass();
        while (class1 != null) {//取父类属性
              fieldList.addAll(Arrays.asList(class1 .getDeclaredFields()));
              class1 = (Class<? extends BeanBase>) class1.getSuperclass(); //父类
        }

        try {
            for (Field field : fieldList) {
                field.setAccessible(true);
                IEnum EnumBase = field.getAnnotation(IEnum.class);
                Object key = field.get(t);//获取字段值
                if (EnumBase != null) {//如果有注解
                    Class<?> clas = EnumBase.clas();
                    Method getName = clas.getDeclaredMethod("getName", Byte.class);//调用getName方法
                    if (key != null) {//值不为空,调用枚举类方法
                        Object[] oo = clas.getEnumConstants();
                        Object invoke = getName.invoke(oo[0],key);
                        tmap.put(field.getName(), key);
                        tmap.put(field.getName() + "Name", invoke);
                    }else {
                        tmap.put(field.getName(), key);
                        tmap.put(field.getName() + "Name", null);
                    }
                }else {//没注解填入原本的值
                    tmap.put(field.getName(), key);
                }
                
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return tmap;
    }
    
    public static JSONObject beanToJson(BeanBase t) {
        Map<String, Object> beanToMap = beanToMap(t);
        JSONObject result = new JSONObject();
        for (String key : beanToMap.keySet()) {
            result.put(key, beanToMap.get(key));
        }
        return result;
    }
}

结果集类Result

import java.util.List;

import com.github.pagehelper.PageInfo;
public class Result {
    private boolean success;
    private String code;
    private String message;
    private Object result;

    public Result() {
        this.success = true;
        this.code = "00000000";
        this.message = "success";
        this.result = "";
    }

    public Result(boolean success, String code, String message, Object result) {
        this.success = success;
        this.code = code;
        this.message = message;
        this.result = result;
    }

    public Result(Object result) {
        this.success = true;
        this.code = "00000000";
        this.message = "success";
        this.result = result;
    }

    public Result(boolean success, String code, String message, List<? extends BeanBase> result) {
        this.success = success;
        this.code = code;
        this.message = message;
        this.result = BeanUtils.ListBeanToJson(result);
    }

    public Result(List<? extends BeanBase> result) {
        this.success = true;
        this.code = "00000000";
        this.message = "success";
        this.result = BeanUtils.ListBeanToJson(result);
    }

    public Result(BeanBase result) {
        this.success = true;
        this.code = "00000000";
        this.message = "success";
        this.result = BeanUtils.beanToJson(result);
    }

    public Result(boolean success, String code, String message, BeanBase result) {
        this.success = success;
        this.code = code;
        this.message = message;
        this.result = BeanUtils.beanToJson(result);
    }

  public Result(String code, String message) {
        this.success = false;
        this.code = code;
        this.message = message;
        this.result = "";
    }

    public boolean isSuccess() {
        return this.success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getResult() {
        return this.result;
    }

    public void setResult(Object result) {
        this.result = result;
    }
}

准备完毕,可以写Controller进行测试了

@RestController
@RequestMapping("/")
public class TestRest {

    @RequestMapping("/test")
    public Result getTestList() {
        Test test1 = new Test();
        test1.setPkey(1);
        test1.setName("测试1");
        test1.setCreatedTime(new Date());
        test1.setEnable((byte) 1);

        Test test2 = new Test();
        test2.setPkey(2);
        test2.setName("测试2");
        test2.setCreatedTime(new Date());
        test2.setEnable((byte) 2);
 
        Test test3 = new Test();
        test3.setPkey(3);
        test3.setName("测试3");
        test3.setCreatedTime(new Date());
        test3.setEnable((byte) 1);

        Test test4 = new Test();
        test4.setPkey(4);
        test4.setName("测试4");
        test4.setCreatedTime(new Date());
        test4.setEnable((byte) 2);

        List<Test> list = new ArrayList<>();
        list.add(test1);
        list.add(test2);
        list.add(test3);
        list.add(test4);

        return new Result(list);
    }

}
@RestController
@RequestMapping("/")
public class TestRest {

    @RequestMapping("/test")
    public Result getTestList() {
        Test test1 = new Test();
        test1.setPkey(1);
        test1.setName("测试1");
        test1.setCreatedTime(new Date());
        test1.setEnable((byte) 1);

        Test test2 = new Test();
        test2.setPkey(2);
        test2.setName("测试2");
        test2.setCreatedTime(new Date());
        test2.setEnable((byte) 2);
 
        Test test3 = new Test();
        test3.setPkey(3);
        test3.setName("测试3");
        test3.setCreatedTime(new Date());
        test3.setEnable((byte) 1);

        Test test4 = new Test();
        test4.setPkey(4);
        test4.setName("测试4");
        test4.setCreatedTime(new Date());
        test4.setEnable((byte) 2);

        List<Test> list = new ArrayList<>();
        list.add(test1);
        list.add(test2);
        list.add(test3);
        list.add(test4);

        return new Result(list);
    }

}

返回前端结果

{
    "code": "00000000",
    "message": "success",
    "result": [
        {
            "updatedTime": null,
            "rowVersion": null,
            "enable": 1,
            "name": "测试1",
            "createdTime": 1552440256286,
            "enableName": "启用",
            "pkey": 1
        },
        {
            "updatedTime": null,
            "rowVersion": null,
            "enable": 2,
            "name": "测试2",
            "createdTime": 1552440256286,
            "enableName": null,
            "pkey": 2
        },
        {
            "updatedTime": null,
            "rowVersion": null,
            "enable": 1,
            "name": "测试3",
            "createdTime": 1552440256286,
            "enableName": "启用",
            "pkey": 3
        },
        {
            "updatedTime": null,
            "rowVersion": null,
            "enable": 2,
            "name": "测试4",
            "createdTime": 1552440256286,
            "enableName": null,
            "pkey": 4
        }
    ],
    "success": true
}

猜你喜欢

转载自www.cnblogs.com/zhyStudy/p/10520990.html