lombok是否可以排除该值,但仍然打印字段名?

wlzqhblo  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(441)

我正在开发一个处理多个敏感值的java应用程序。我们使用的是lombok,有很多数据类如下所示。然而,在日志中看到这些类却没有显示它们包含一些关键字段,这是令人困惑的,因为生成的tostring将100%忽略排除的字段。有没有可能有Lombok山的印刷品 clientSecret=<HIDDEN> 没有为每个类编写自定义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;
}
eimct9ow

eimct9ow1#

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

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(" "));

    }
}

还有一节课:

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);
}
gopyfrb3

gopyfrb32#

您可以排除应屏蔽的字段,并包含返回屏蔽值的助手方法:

@Data
public class TokenReq {

    @ToString.Exclude
    private String clientSecret;

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

相关问题