如何通过Java反射机制建一个实体的属性和属性中文含义以列表的形式返回给前端

1、建一个实体类,并用@ApiModelProperty注解标注中文含义
package com.example.demo.model.dto;

import com.example.webcore.framework.converter.Convert;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@ApiModel("人员字段信息")
public class BdPersonDto extends Convert {

    @ApiModelProperty(value = "人员ID")
    private String fid;
    @ApiModelProperty(value = "人员姓名")
    private String fnameL2;
    @ApiModelProperty(value = "描述")
    private String fdescriptionL2;
    @ApiModelProperty(value = "性别")
    private Integer fgender;
    @ApiModelProperty(value = "邮箱")
    private String femail;
    @ApiModelProperty(value = "手机号码")
    private String fcell;
    @ApiModelProperty(value = "创建时间")
    private LocalDateTime fcreatetime;
    @ApiModelProperty(value = "最后修改时间")
    private LocalDateTime flastupdatetime;
    @ApiModelProperty(value = "个人邮箱")
    private String cfpersonalemail;
    @ApiModelProperty(value = "公司邮箱")
    private String cfcompanyemail;
    @ApiModelProperty(value = "用户名")
    private String cfusername;

}
2、写一个方法,判断是否存在ApiModelProperty注解
 @Override
    public List    getFields() {
        List fieldOptionList = new ArrayList<>();
        BdPersonDto bdPersonDto = new BdPersonDto();
        Field[] declaredFields = bdPersonDto.getClass().getDeclaredFields();
        Stream stream = Arrays.stream(declaredFields);
        stream.forEach(it ->{
            //判断是否用了ApiModelProperty注解,用了的话就将中文名取出来
            if(it.isAnnotationPresent(ApiModelProperty.class)){
                ApiModelProperty declaredAnnotation = it.getDeclaredAnnotation(ApiModelProperty.class);
                //获取中文属性
                String value = declaredAnnotation.value();
                //获取英文属性
                String key = it.getName();
                PersonFieldOptionDTO fieldOptionDTO = new PersonFieldOptionDTO();
                fieldOptionDTO.setKey(key);
                fieldOptionDTO.setName(value);
                fieldOptionList.add(fieldOptionDTO);
            }
        });
        return fieldOptionList;
    }

然后封装看效果返回的是一个key和name键值对的list集合

你可能感兴趣的:(Java后端开发,java,开发语言,java反射)