Skip to content
Advertisement

How to generate annotations and use lombok with javapoet?

Is there any way (and any sense) to use Lombok when I am using javapoet?
Here is example:

TypeSpec typeSpec = TypeSpec
        .classBuilder("MyDtoWithLombok")
        .addModifiers(Modifier.PUBLIC)
        //.addAnnotation(NoArgsConstructor.class)
        //.addAnnotation(AllArgsConstructor.class)
        //.addAnnotation(Data.class)
        //.addAnnotation(Builder.class)
        .addField(...)
        .build();

When I am trying to add Lombok annotation (like that -> Data.class”) I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: lombok/NoArgsConstructor
...
Caused by: java.lang.ClassNotFoundException: lombok.NoArgsConstructor
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 3 more

Advertisement

Answer

Probably because Lombok is usually given provided scope – you ordinarily don’t want it on the classpath, because it’s supposed to be processed and removed at compile-time.

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
    <scope>provided</scope>
</dependency>

Remove the <scope>provided</scope> line, or change it to compile. Both are equivalent, since compile is the default.

I would personally explicitly use compile and maybe even add a comment explaining why you’re not using provided, since a casual reader might think it’s a mistake otherwise, and maybe try to change it to provided again.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement