需求场景
对于特定字段进行脱敏
实现步骤
首先创建注解@interface
1 import java.lang.annotation.ElementType; 2 import java.lang.annotation.Retention; 3 import java.lang.annotation.RetentionPolicy; 4 import java.lang.annotation.Target; 5 6 @Retention(RetentionPolicy.RUNTIME) 7 @Target(ElementType.FIELD) 8 public @interface DesenStr { 9 10 }
其次创建注解操作的类
import java.lang.reflect.Field; public class AnnotationClass { public Object parse(Object o) { Class<?> mClass = null; Object o1 = o; try { mClass = o.getClass(); Field[] fields = mClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(DesenStr.class)) { field.setAccessible(true); String s = String.valueOf(field.get(o1)); String replace = StringUtil.desen(s.trim());// 脱敏 field.set(o1, replace); } } } catch (IllegalAccessException e) { e.printStackTrace();// 此处可自定义打印日志 } return o1; } }
有的小伙伴需要明确替换的char,可以用
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DesenStr { String source() default ""; String target() default ""; }
import com.dxinfor.mini.ebill.utils.StringUtil; import java.lang.reflect.Field; public class AnnotationClass { public Object parse(Object o) { Class<?> mClass = null; Object o1 = o; try { mClass = o.getClass(); Field[] fields = mClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(DesenStr.class)) { field.setAccessible(true); DesenStr annotation = field.getAnnotation(DesenStr.class); String source = annotation.source();// 待匹配 String target = annotation.target();// 替换为 String s = String.valueOf(field.get(o1)); String replace = s.replace(source,target); field.set(o1, replace); } } } catch (IllegalAccessException e) { e.printStackTrace(); } return o1; } }
随后在需要替换的成员变量上加上注解 @DesenStr
@Data @AllArgsConstructor @NoArgsConstructor public class UserInfo{ @DesenStr private String userId; private String userName; }
再在使用的地方调用parse方法进行脱敏(此处可以写成AOP)
为了方便就暂时用@Test演示
@Test void parse(){ UserInfo userInfo= new UserInfo ("1328223342","张三"); System.out.println(userInfo);// 1328223342 张三 Object parseObject = new AnnotationClass().parse(userInfo); if(parseObject instanceof UserInfo){ UserInfo newUserInfo = (UserInfo) parseObject; System.out.println(newUserInfo);// 132****342 张三 } }
标签:lang,java,String,自定义,demo,field,import,注解,annotation From: https://www.cnblogs.com/onejay/p/18155177