【问题标题】:Lombok annotations give Malicious code error - May expose internal representation by returning reference to mutable object errorLombok 注释给出恶意代码错误 - 可能通过返回对可变对象的引用来暴露内部表示错误
【发布时间】:2021-07-09 05:43:28
【问题描述】:

我有以下课程。

// Adding Lombok's @Data / @Value gives an error
public class Sample {

    String id;

    String name;

    Dummy[] entries;

    @JsonCreator
    // @Builder --> This gives same error
    private Sample(
            @JsonProperty("id") final String id,
            @JsonProperty("name") final String name,
            @JsonProperty("entries") @NonNull final Dummy[] entries) {
        this.id = id;
        this.name = name;
        this.entries = entries;
    }
}

如果我添加 Lomobok 注释,我会收到以下错误。我们严重依赖 Lombok,我正在尝试弄清楚如何确保不返回可变对象。

EI_EXPOSE_REP: May expose internal representation by returning reference to mutable object

EI_EXPOSE_REP2: May expose internal representation by incorporating reference to mutable object

作为替代方案,我可以使用 List 而不是 Array 并依赖 @Singular 注释。但我想知道带有 Lombok 注释的 Array 是否有解决方法。

【问题讨论】:

  • 感谢您的评论!但是它并没有解决我的问题,因为我依赖 Lombok 来实现 @Builder、Getter 和 Setter。所以我试图找出龙目岛是否可以使用数组?
  • Afaik 在 lombok 中不可能配置为生成不可变数组。您可以尝试使用Arrays.copyOf 自行为该字段实现getter。但我不确定这会有所帮助。
  • 手写就行了。

标签: java lombok


【解决方案1】:

解决此问题的一种方法是添加一些 lombok 配置。这样做的方法是在项目的根目录(你的 pom.xml/build.gradle 所在的地方)添加一个名为:

lombok.config.

在此文件中添加以下行:

config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true
lombok.extern.findbugs.addSuppressFBWarnings = true
lombok.anyConstructor.addConstructorProperties = true

更多信息在这里: https://projectlombok.org/features/configuration

【讨论】:

    【解决方案2】:

    Lombok 生成的返回或接受可变对象或结构的方法是一个众所周知的老问题。 例如this issue about Date 于 2015 年提交。
    Lombok 不太可能解决这个问题,因为它很重要。 您的选择:

    1. 通过构建工具插件或 IDE 配置禁用特定的 FindBugs/SpotBugs 检查。
    2. 将带有相关错误代码的@SuppressFBWarnings 放在违规类上。
    3. 使用onX Lombok 功能让它将@SuppressFBWarnings 放置在违反方法(setter、getter 等)上,如下面的 sn-p 所示。
    @Data
    @Setter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2","EI_EXPOSE_REP"}))
    @Getter(onMethod_ = @SuppressFBWarnings({"EI_EXPOSE_REP2","EI_EXPOSE_REP"}))
    public class TheClass {
        private MutableClassOrStructure classOrStructure;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      相关资源
      最近更新 更多