Skip to content
astrapi69 edited this page Mar 25, 2015 · 8 revisions

@ExtensionMethod

Overview

An annotation that allows you to use extension methods in Java. Simply annotate a class with it to import static methods of another class and use them as extension methods.

Example

With Lombok

import lombok.ExtensionMethod;
import java.util.Arrays;

// here we are importing java.util.Arrays and a custom Objects class (seen below) 
@ExtensionMethod({Arrays.class, Objects.class})
class ExtensionMethodExample {

  // example of null coalescence in Java
  private void print(String name) {
    // "Joe Doe" if name is null
    String value = name.orElse("John Doe"); 
    System.out.println(value); 
  }

  // example of multiple chained extension methods
  private void copySort() {
    long[] values = new long[] { 5, 9, 2, 7 };

    // use Array static methods as extension methods
    values.copyOf(3).sort();
  }
  
  // example of how to write your own extension methods
  private boolean customExtension(String s) {
    return s.isOneOf("foo", "bar");
  }
}  

// This is an example of class you would provide.
// You must use static methods and the type of the first argument determines 
// which objects these methods can be applied to. If you use object, the
// method would appear in code completion for all reference objects.
class Objects {

  // returns true if one of the possible values 
  public static boolean isOneOf(Object object, Object[] values) {
    if (values != null) 
      for (Object value : values) 
         if (object.equals(value))
            return true;
    
    // not found in values array
    return false;
  }

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

Vanilla Java

import java.util.Arrays;

class ExtensionMethodExample {

  private void print(String name) {
    // ugly if/else statement
    if(name == null)
       System.out.println("John Doe");
    else
       System.out.println(name);
  }

  private void copySort() {
    long[] values = new long[] { 5, 9, 2, 7 };
    // ugly chaining of static methods
    Arrays.sort(Arrays.copyOf(values, 3));
  }
  
  private boolean customExtension(String s) {
    // static method call
    Object[] values = {"foo", "bar"};
    return ExtensionMethodExample.Objects.isOneOf(s, values);
  }
  
}

class Objects {
  // remains unchanged, as above
}

Behind the Scenes

(Documentation pending)

TODO:

  • explain how we find extension methods
  • explain that we have a working Content-Assist for this feature in eclipse (key selling point)

Configuration

(Documentation pending)

TODO:

  • explain parameter suppressBaseMethods