How I can use Lombok annotation in JShell?
I tried
* jshell --class-path lombok.jar
jshell> import lombok.*
jshell> @Data class Person { String name; String address; }
| created class Person
jshell> new Person()
$3 ==> Person@6f7fd0e6
jshell> $3.setName("Hi")
| Error:
| cannot find symbol
| symbol: method setName(java.lang.String)
| $3.setName("Hi")
| ^--------^
CodePudding user response:
It won't work. JShell doesn't support annotation processors as would be needed to make the Lombok annotations to work as expected.
See JDK-8213600 - JShell compilation does not take Lombok's annotation processor into account
For a workaround, see https://stackoverflow.com/a/74084467/139985 or the bug report itself.
Basically, you need to compile the Lombok code outside of jshell, and then import the compiled classes into your jshell session.
CodePudding user response:
This is currently not possible as described by this bug report.
The workaround that is mentioned there is to compile your class externally. For that, you basically have to follow the following steps:
- Create some directory, e.g.
com/example
. - Put the
Person
class below in that directory.
package com.example;
import lombok.*;
@Data
public class Person {
private String name;
private int age;
}
- Compile the class with:
javac -cp lombok.jar com/example/Person.java
- Create an archive with:
jar -cf person.jar com/
- Run JShell:
jshell --class-path "person.jar:lombok.jar"
- Create a
Person
:
> import com.example.*;
> var p = new Person();
Also note that JShell cannot access classes that are in the default package (as described here) which is why we put Person
in com.example
.