Lombok 可以排除该值但仍然打印字段名称吗?

Can Lombok exclude the value but still print the field name?

我正在开发一个处理多个敏感值的 Java 应用程序。我们正在使用 Lombok,并且有很多数据 classes,如下所示。然而,在日志中看到这些 classes 并没有迹象表明它们包含一些关键字段令人困惑,因为生成的 toString 将 100% 忽略排除的字段。是否可以让 Lombok 打印类似 clientSecret=<HIDDEN> 的内容,而无需为每个 class 编写自定义 toString?

/** data we will send to token endpoint */
@Data
public class TokenReq {
    private String grantType;

    private String code;

    private String clientId;

    @ToString.Exclude
    private String refreshToken;

    @ToString.Exclude
    private String clientSecret;

    private String redirectUri;
}

如评论中所述,这是我前一段时间的做法,可能需要更多工作,但我的想法是:

interface ToString {

    default String innerToString(String... exclusions) {
        Method[] allMethods = getClass().getDeclaredMethods();
        return Arrays.stream(allMethods)
                     .filter(x -> x.getName().startsWith("get"))
                     .map(x -> {
                         if (Arrays.stream(exclusions).anyMatch(y -> ("get" + y).equalsIgnoreCase(x.getName()))) {
                             return x.getName().substring(3) + " = <HIDDEN>";
                         }

                         try {
                             return x.getName().substring(3) + " = " + x.invoke(this);
                         } catch (Exception e) {
                             throw new RuntimeException(e);
                         }
                     })
                     .collect(Collectors.joining(" "));

    }
}

还有一个class:

static class Person implements ToString {

    private String name;
    private String password;

    // constructor/getter or lombok annotations

    public String toString() {
        return innerToString("password");
    }
}

然后用法:

public static void main(String[] args) {
    Person p = new Person("eugene", "password");
    System.out.println(p);
}

您可以排除应该屏蔽的字段并包含一个辅助方法 returns 屏蔽值:

@Data
public class TokenReq {

    @ToString.Exclude
    private String clientSecret;

    @ToString.Include(name="clientSecret")
    private String hiddenClientSecretForToString() {
        return "<HIDDEN>";
    }
}