No, vanilla Java does not use extension methods. However, Lombok adds many useful features - including the syntax of extension methods - thanks to its comments and bytecode generation.
You can use @ExtensionMethod annotations to "convert" existing static methods to extension methods. The first parameter of static methods basically becomes this . For example, this is valid Java code enhanced by Lombok:
import lombok.experimental.ExtensionMethod; @ExtensionMethod({java.util.Arrays.class, Extensions.class}) public class ExtensionMethodExample { public String test() { int[] intArray = {5, 3, 8, 2}; intArray.sort(); String iAmNull = null; return iAmNull.or("hELlO, WORlD!".toTitleCase()); } } class Extensions { public static <T> T or(T obj, T ifNull) { return obj != null ? obj : ifNull; } public static String toTitleCase(String in) { if (in.isEmpty()) return in; return "" + Character.toTitleCase(in.charAt(0)) + in.substring(1).toLowerCase(); } }
Note that Lombok extension methods can be “called” for null objects; if the static method does not have a null value, a NullPointerException will not be thrown, as this basically translates to calling a static method. Yes - it comes down to syntactic sugar, but I think it is even more readable than regular static method calls.
In addition, you can use some other Java compatibility JVM languages if this is OK in your project. For example, Kotlin comes with extension method functions , as well as some useful extensions already defined in the standard library. Here is a comparison of Kotlin and Lombok .
source share