-
Notifications
You must be signed in to change notification settings - Fork 44
@Action
Encapsulates a method that does not return a value, so its signature looks like this:
public void methodName(T1 t1, T2 t2, ..., Tn tn)
import lombok.ExtensionMethod;
import lombok.Action;
import lombok.Actions.Action1;
@ExtensionMethod(Operations.class)
public class Main {
public static void main(final String[] args) {
"Hello World".andThen(println());
}
@Action
private static void println(final Object o) {
System.out.println(o);
}
}
public class Operations {
public static <T> void andThen(final T value, final Action1<T> andThen) {
if (value != null) andThen.apply(value);
}
}
import lombok.Actions.Action1;
public class Main {
public static void main(String[] args) {
Operations.andThen("Hello World", println());
}
private static Action1<Object> println() {
return new Action1<Object>() {
public void apply(final Object o) {
System.out.println(o);
}
};
}
}
public class Operations {
public static <T> void andThen(final T value, final Action1<T> andThen) {
if (value != null) andThen.apply(value);
}
}
By default @Action
uses lombok.Actions
as template class. This means you need some lombok-pg classes at runtime. These runtime dependencies are located in lombok-pgs runtime artefact called lombok-pg-runtime.jar
.
As a benefit of using lombok.Actions
you get type information for free, which is accessible via getter methods such as: Class<?> getParameterType1() ... Class<?> getParameterTypeN()
on the action objects.
If you want to avoid having a runtime dependency to lombok-pg or just want to define you own template, use @Action(template=MyActionTemplate.class)
and make sure that MyActionTemplate satisfies the following conditions:
- The template class and any accessible (meaning public static) inner class qualifies as a possible template if they are abstract classes or interfaces that have only one abstract public method.
- The type arguments of the abstract method have to match the type arguments of the surrounding type.
- A template class must not define multiple templates for the same argument count.
Template Example: lombok.Actions (source)
Being able to specify a template class also allows you to use @Action
with other libraries such as commons-collections @Action(template=org.apache.commons.collections.Closure.class)
.
I am not able to run @Action. If I provide Action1 implementation it works.
implementation private static Action1 println() { return new Action1() { public void apply(final Object o) { System.out.println(o); } };
pom : com.github.peichhorn lombok-pg 0.11.3
<dependency>
<groupId>com.github.peichhorn</groupId>
<artifactId>lombok-pg</artifactId>
<version>0.11.3</version>
<classifier>runtime</classifier>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>