有时候我们在打日志的时候,希望对象中有些字段不显示出来,此时可以考虑自定义一个注解。
比如,自定义一个注解GsonIgnoreField如下

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GsonIgnoreField {
}

然后定义一个GsonUtil类

public class GsonUtil {
    static Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            Object object = f.getAnnotation(GsonIgnoreField.class);
            return object != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> incomingClass) {
            return false;
        }
    }).create();

    public static String toGsonString(Object object){
        return gson.toJson(object);

    }
}

假设此处我们不想将Person的age属性显示出来,可以在age上加上@GsonIgnoreField属性。

@Data
public class Person {
    private String name;
    @GsonIgnoreField
    private int age;

}

测试一下

 @Test
    public void test1(){
        Person person = new Person();
        person.setAge(11);
        person.setName("reed");
        System.out.println(GsonUtil.toGsonString(person));
    }

运行结果如下
{“name”:“reed”}