1.自定义注解
package com.xxx.common.annotation;
import java.lang.annotation.*;
/**
* 对象属性上加上该注解表示参与计算对象数据完整度
*
* @author hcx
*/
@Documented // 说明该注解将被包含在javadoc中
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Target({ElementType.FIELD}) // 作用在对象属性上
public @interface DataCompleteAnnotation {
}
2.Cust类加上@DataCompleteAnnotation
/**
* 客户 实体
*
* @author hcx
*/
@Data
public class Cust implements Serializable {
@DataCompleteAnnotation
@ApiModelProperty(value = "姓名")
private String name;
@DataCompleteAnnotation
@ApiModelProperty(value = "手机")
private String phone;
@DataCompleteAnnotation
@ApiModelProperty(value = "性别: [1=男, 2=女]")
private Integer sex;
//...省略其他字段
}
3.方法
/**
* 获取对象资料完整度
*
* @author hcx
*/
public static <T> double getDataComplete(T t){
// 总属性数量
int total = 0;
// 有效属性数量
int count = 0;
// 获取所有属性
// getDeclaredFields 不包含父类,包含私有属性
// getFields 包含父类属性
Field[] fields = t.getClass().getDeclaredFields();
for (Field field : fields) {
try {
// 设置私有属性的访问权限
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = field.get(t);
Class<?> fieldType = field.getType();
if (field.isAnnotationPresent(DataCompleteAnnotation.class)){
if (ObjectUtils.isEmpty(fieldValue)){
continue;
}
// 判断属性具体类型
if (fieldType == Integer.class){
Integer integerValue = (Integer) fieldValue;
if (!integerValue.equals(0)){
count++;
}
}else if (fieldType == String.class){
String stringValue = (String) fieldValue;
if (StringUtils.isNotBlank(stringValue)){
count++;
}
}else if (fieldType == BigDecimal.class){
BigDecimal bigDecimalValue = (BigDecimal) fieldValue;
if (!(BigDecimal.ZERO.compareTo(bigDecimalValue) == 0)){
count++;
}
}else if (fieldType == Date.class){
Date dateValue = (Date) fieldValue;
if (!ObjectUtils.isEmpty(dateValue)){
count++;
}
}// ...省略其他类型的判断
total++;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 保留2位小数
double d = (double) count / total * 100;
BigDecimal bigDecimal = new BigDecimal(d);
return bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
}
4.调用
@Test
public void test02() {
// 随便new一个对象,进行测试
Cust cust = new Cust();
cust.setName("张三");
cust.setSex(0);
cust.setCreateTime(new Date());
double dataComplete = XiNaioTest.getDataComplete(cust);
System.out.println("dataComplete = " + dataComplete);
}