Skip to content
peichhorn edited this page Jun 30, 2012 · 9 revisions

@Action

Overview

Encapsulates a method that does not return a value, so its signature looks like this:

public void methodName(T1 t1, T2 t2, ..., Tn tn) 

Example

With Lombok

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);
  }
}

Vanilla Java

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);
  }
}

Behind the Scenes

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.

Configuration

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).

Clone this wiki locally