Home > Enterprise >  jshell: How to use Lombok in jshell?
jshell: How to use Lombok in jshell?

Time:10-16

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:

  1. Create some directory, e.g. com/example.
  2. Put the Person class below in that directory.
package com.example;

import lombok.*;

@Data
public class Person {
    private String name;
    private int age;
}
  1. Compile the class with:
javac -cp lombok.jar com/example/Person.java 
  1. Create an archive with:
jar -cf person.jar com/
  1. Run JShell:
jshell --class-path "person.jar:lombok.jar"
  1. 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.

  • Related