projectlombok / lombok

Very spicy additions to the Java programming language.
https://projectlombok.org/
Other
12.88k stars 2.39k forks source link

[BUG] @Nullable on field with lazy getter incorrectly applied to field #3720

Closed GregDThomas closed 1 month ago

GregDThomas commented 2 months ago

Describe the bug If you mark a field with a lazy getter as @Nullable, the generated code results in the field being marked as Nullable, even though it's not (it's turned in to an AtomicReference). This trips up some static analysis (e.g. spotbugs).

To Reproduce

Consider the following lombok code;

        @Nullable
        @Getter(lazy=true)
        private final Double cached = expensive();

        @Nullable
        private Double expensive() {
            final double[] results = new double[1000000];
            for (int i = 0; i < result.length; i++) {
                results[i] = Math.asin(i);
            }
            return results[results.length - 1] == 0
                ? null
                : results[results.length - 1];
        }

This generates:

        @Nullable
        private final AtomicReference<Object> cached = new AtomicReference();

        @Nullable
        @Generated
        public Double getCached() {
            Object $value = this.cached.get();
...
        }

Because the cached field is marked @Nullable, spotbugs (and possible others) identify the line Object $value = this.cached.get(); as problematic,

Expected behavior I can see two possible solutions to this - no doubt others exists!

  1. Lombok removes the @Nullable annotation from the cached field, but retains it on the getCached() method.
  2. There's a way to supply the @Nullable to the @Getter annotation, so that the @Nullable is only applied to the method not the field.

Version info (please complete the following information):

GregDThomas commented 2 months ago

And another option;

  1. Because the expensive() method is marked as @Nullable, lombok carried this annotation through to the getter method that it generates, removing the need to mark the field as @Nullable.
GregDThomas commented 1 month ago

I've also just discovered the lombok.extern.findbugs.addSuppressFBWarnings = true setting which pretty much solves this, so closing the issue.