This is the old documentation of lombok-pg. The new version can be found in the wiki of the github repository. Take me to the new Version then!

@ExtensionMethod

Overview

This annotation allows you to use extension methods in Java.

With Lombok

01 import lombok.ExtensionMethod;
02 import java.util.Arrays;
03 
04 @ExtensionMethod({Arrays.class, ExtensionMethodExample.Objects.class})
05 class ExtensionMethodExample {
06   private void arrayExtension() {
07     long[] values = new long[] { 592};
08     values.copyOf(3).sort();
09   }
10   
11   private boolean customExtension(String s) {
12     return s.isOneOf("foo""bar");
13   }
14   
15   static class Objects {
16     public static boolean isOneOf(Object object, Object... possibleValues) {
17       if (possibleValues != nullfor (Object possibleValue : possibleValues) {
18         if (object.equals(possibleValue)) return true;
19       }
20       return false;
21     }
22   }
23 }

Vanilla Java

01 import java.util.Arrays;
02 
03 class ExtensionMethodExample {
04   private void arrayExtension() {
05     long[] values = new long[] { 592};
06     Arrays.sort(Arrays.copyOf(values, 3));
07   }
08   
09   private boolean customExtension(String s) {
10     return ExtensionMethodExample.Objects.isOneOf(s, "foo""bar");
11   }
12   
13   static class Objects {
14     public static boolean isOneOf(Object object, Object... possibleValues) {
15       if (possibleValues != nullfor (Object possibleValue : possibleValues) {
16         if (object.equals(possibleValue)) return true;
17       }
18       return false;
19     }
20   }
21 }

Small print

A recent update allows usage of this in generic methods. For example, here's a null coalescing extension method:


// given this code
public static  T orElse(final T value, final T elseValue) {
return value != null ? value : elseValue;
}


String name = null;
String value = name.orElse("John Doe"); // value is "John Doe"