Skip to content
peichhorn edited this page Jul 19, 2012 · 2 revisions

@Predicate

Overview

Encapsulates a method that returns a boolean value, so its signature looks like this:

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

Example

With Lombok

import static lombok.Yield.yield;
import java.util.Arrays;
import lombok.ExtensionMethod;
import lombok.Predicate;
import lombok.Predicates.Predicate1;

@ExtensionMethod({Arrays.class, Extensions.class})
public class Main {

  public static void main(final String[] args) {
	args.asList().filter(isEmpty());
  }

  @Predicate
  private static boolean isEmpty(final String s) {
    return s == null || s.isEmpty();
  }
}

public class Extensions {

  public static <T> Iterable<T> filter(final Iterable<T> list, final Predicate1<T> filter) {
    for (T element : list) if (filter.evaluate(element)) yield(element);
  }
}

Vanilla Java

package distantworlds.util;

import java.util.Arrays;
import lombok.Predicates.Predicate1;

public class Main {
  public static void main(String[] args) {
    Extensions.filter(Arrays.asList(args), isEmpty());
  }

  private static Predicate1<String> isEmpty() {
    return new Predicate1<String>() {
      public boolean evaluate(String s) {
        return (s == null) || (s.isEmpty());
      }
    };
  }
}

public class Operations {
  // not affected by @Predicate
}

Behind the Scenes

By default @Predicate uses lombok.Predicates 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.Predicates you get type information for free, which is accessible via getter methods such as: Class<?> getParameterType1() ... Class<?> getParameterTypeN() on the predicate objects.

Configuration

If you want to avoid having a runtime dependency to lombok-pg or just want to define you own template, use @Predicate(template=MyPredicateTemplate.class) and make sure that MyPredicateTemplate 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.Predicates (source)

Being able to specify a template class also allows you to use @Predicate with other libraries such as commons-collections @Predicate(template=org.apache.commons.collections.Predicate.class).