Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lombok annotations give Malicious code error - May expose internal representation by returning reference to mutable object error

Tags:

java

lombok

I have the following class.

// 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;
    }
}

If I add Lomobok annotations, I get the following error. We heavily rely on Lombok and I am trying to figure out how I can ensure I don't return a mutable object.

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

As an alternative, I could use List instead of Array and rely on @Singular annotation. But I would like to know if there is a workaround for Array with Lombok's annoations.

like image 438
SyncMaster Avatar asked Mar 12 '26 02:03

SyncMaster


2 Answers

One way to solve this is to add some lombok config. The way to do this is in the root of the project (the same place your pom.xml/build.gradle is) add a file called:

lombok.config.

In this file add the following lines:

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

More info here: https://projectlombok.org/features/configuration

like image 142
theINtoy Avatar answered Mar 13 '26 15:03

theINtoy


It's an old and well known problem with methods generated by Lombok that return or accept mutable objects or structures. For example this issue about Date was submitted in 2015.
It is unlikely that Lombok will ever fix this because it's non-trivial. Your options :

  1. Disable particular FindBugs/SpotBugs inspection via build tool plugin or IDE configuration.
  2. Place @SuppressFBWarnings with relevant error code on violating class.
  3. Use onX Lombok feature to let it place @SuppressFBWarnings on violating methods(setters,getters etc.) like in snippet below.
@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;
}
like image 40
Aleksandr Kravets Avatar answered Mar 13 '26 14:03

Aleksandr Kravets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!