1、注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author Minco
* @Date 8:44 2020-07-24
* @Description 价格控制数据注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PriceLimit {
/**
* 字段类型(0:不限制;1:进价类权限限制;2:价格类权限限制)
*/
Type type() default Type.ALL;
public enum Type {
ALL(0), JLIMIT(1), LIMIT(2);
private final int value;
Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
}
2、实体类
import com.hieasy.comm.annotation.PriceLimit;
import lombok.Data;
@Data
public class Xssj {
@PriceLimit(type = PriceLimit.Type.LIMIT)
private String xsje;
@PriceLimit(type = PriceLimit.Type.JLIMIT)
private String bzjje;
@PriceLimit(type = PriceLimit.Type.JLIMIT)
private String mlr;
@PriceLimit(type = PriceLimit.Type.JLIMIT)
private String mll;
private double pjzk;
private double tbl;
private double hbl;
private String dxdm;
private String dxmc;
private String type;
private int sl;
@PriceLimit(type = PriceLimit.Type.LIMIT)
private String je;
@PriceLimit(type = PriceLimit.Type.JLIMIT)
private String mlrqn; //去年毛利润
@PriceLimit(type = PriceLimit.Type.JLIMIT)
private String mlrsy; //上月毛利润
}
3、工具类
public <T> void fltPriceLimit(Object object,SysUserLimit limit) throws Exception {
Field[] fields = object.getClass().getDeclaredFields(); // 获取实体类的所有属性,返回Field数组
for(Field field:fields){
PriceLimit attr = field.getAnnotation(PriceLimit.class);
Integer type=0;
if(null!=attr) type=attr.type().value();
if(type==1) {
if(limit.getLimitJPriceShow()==1 || limit.getLimitPriceShow()==1) {
if(field!=null){
field.setAccessible(true);//修改作用域
field.set(object,"***");//设置值
}
}
}else if(type==2){
if(limit.getLimitPriceShow()==1) {
if(field!=null){
field.setAccessible(true);//修改作用域
field.set(object,"***");//设置值
}
}
}
}
}
4、测试
public static void main(String[] args) throws Exception{
SysUserLimit limit=new SysUserLimit();
limit.setLimitJPriceShow(1);
limit.setLimitPriceShow(0);
Xssj xssj=new Xssj();
System.out.println("原对象:"+xssj);
CommonService commonService=new CommonServiceImpl();
commonService.fltPriceLimit(xssj,limit);
System.out.println("过滤对象:"+xssj);
}
5、输出结果
6、扩展
此类方法还可以应用到非整形的数据格式化..