In Swift, you can create extension of existing class to add additional functions to the existing class whenever it is needed. This also helps to avoid creating a subclass of the existing class.
I was just wondering if there is a similar function exist in Java? or is it the only way to add additional methods to a existing Java class is to create a subclass of the existing class?
No, vanilla Java does not feature extension methods. However, Lombok adds many useful features - including extension methods syntax - thanks to its annotations and bytecode generation.
You can use its @ExtensionMethod annotations to "convert" existing static methods to extension methods. The first parameter of the static methods basically becomes this
. For example, this is a valid Lombok-enhanced Java code:
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 "invoked" on null objects - as long as the static method is null-safe, NullPointerException
will not be thrown, as this is basically translated to static method call. Yes - it comes down to syntax sugar, but I guess this is still more readable than the usual static methods calls.
Aside from that, you can use some other JVM language with Java interoperability, if that's OK in your project. For example, Kotlin comes with extension methods functionality, as well as some useful extensions already defined in the standard library. Here's a Kotlin and Lombok comparison.