1.创建注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Security {
String type() default "dh";
}
2.属性加入注解
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private int age;
private Card card;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Card {
private String cardNo;
@Security
private String password;
private Person person;
}
3.解析和测试注解
public class Test {
public static void main(String[] args) throws IllegalAccessException {
Card card = new Card("123456", "Abc123++", new Person("aaa", 12, new Card("123", "999", null)));
Person person = new Person("sean", 12, card);
encryPwd(person);
System.out.println(person);
}
public static void encryPwd(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field == null||field.getType()==null) {
continue;
}
field.setAccessible(true);
if (null == field.get(obj)) {
continue;
}
if (field.isAnnotationPresent(Security.class) && field.getType().equals(String.class)) {
String type = field.getAnnotation(Security.class).type();
switch (type) {
case "dh":
field.set(obj, "ttt" + field.get(obj));
break;
default:
break;
}
} else if (!field.getType().isPrimitive() && null != field.getType().getDeclaredFields() && field.getType().getDeclaredFields().length > 0) {
encryPwd(field.get(obj));
}
}
}
}
注:该注解加密只能用于String字符串类型的属性进行加密