How to use @UtilityClass lombok annotation on inner class in Eclipse IDE

Viewed 2533

I have a class where @UtilityClass annotation on class C and class D gives error in eclipse IDE but works fine with IntelliJ

@UtilityClass automatically makes the class static, however, this class cannot be made static.

Not able to use @UtilityClass annotation on class C and class D. Lombok v1.18.20 "Envious Ferret" is installed.

 @UtilityClass
    public class A {
    
        @UtilityClass
        public class B {
    
            public final String name = "name";
            public final String id = "id";
    
            @UtilityClass
            public class C {
    
                public final String OVER = "over.draft";
                public final String ADD = "add.draft";
            }
    
            @UtilityClass
            public class D {
    
                public final String OVER = "over.published";
                public final String ADD = "add.published";
            }
        }
    }
2 Answers

Looks like a bug if it is not working in eclipse and working in Intellij.

The doc for @UtilityClass states that all methods, inner classes and fields in the class would be marked as static, if we use this annotation. Going by that, class B should become static.

Now looking at the code (lombok.javac.JavacNode) from where the error mentioned in question is thrown, the code comment says that:

// It might be an inner class. This is okay, but only if it is / can be a
// static inner class. Thus, all of its parents have to be static inner classes
// until the top-level.

So if @UtilityClass annotation is used on class C then class B should be static for it to work.

Since class A is annotated with @UtilityClass, class B should have become static, but may be, it is not recognized as static during the above mentioned validation.

To fix this, you need to manually add static to class B. (Project build might also be required).

(You may also log a bug in the lombok github page)

Make sure your JDK version isn't above version 8(1.8), cause looks like there is a bug in lombok, that @UtilityClass doesn't make inner classes static when JDK 9 or higher

Related