Skip to content

Instantly share code, notes, and snippets.

@dylon
Created September 15, 2013 05:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylon/6568211 to your computer and use it in GitHub Desktop.
Save dylon/6568211 to your computer and use it in GitHub Desktop.
Demonstrates how to use lombok's @ExtensionMethod annotation on objects and primitive types.
import lombok.ExtensionMethod;
@ExtensionMethod(Extensions.class)
public class ExtensionMethodTest {
public static void main(final String... args) {
System.out.println(args.isNull()); //-> false
System.out.println(null.isNull()); //-> true
int i = 0;
System.out.println(i.isNull()); //-> false
// NOTE: i.isNull() works because calling a method on a reference is valid
// syntactically, even if Java does not natively support calling methods on
// primitive types. Lombok will rewrite the statement before the compiler
// performs sematic analysis on what type of a reference "i" is and whether
// it is valid to invoke a method on it.
//
// NOTE: 0.isNull() will not work because it is a syntax error to invoke a
// method on a numeric literal.
}
}
class Extensions {
public static boolean isNull(final String[] array) {
return null == array;
}
public static boolean isNull(final int i) {
return false;
}
}
@ungood
Copy link

ungood commented Sep 27, 2013

Very nice, though still not as nice as other languages :) (Specifically, having to annotate the class calling the extension methods, and not being able invoke methods on literals).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment