Does Java support Swift-like class extensions?

In Swift, you can create an extension of an existing class to add additional functions to an existing class whenever necessary. It also helps to avoid subclassing an existing class.

I'm just wondering if a similar function exists in Java? or is the only way to add additional methods to an existing Java class is to subclass the existing class?

+7
source share
4 answers

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 .

+5
source

The manifest provides full, seamless support for C # -style extension methods for Java , allowing you to add methods to classes that you do not control, such as java.lang.String .

Demo: http://manifold.systems/images/ExtensionMethod.mp4

Learn more:
http://manifold.systems/docs.html
https://github.com/manifold-systems/manifold

+3
source

The Decorator Pattern is perhaps the closest match. It uses an interface to support compatibility and composition of a type to enhance an existing class function. This is not the same principle as the one you describe, but it can serve the same purpose.

+2
source

This can be done in other languages ​​for the JVM, such as Scala, Groovy or Closure.

For example in Groovy:

 List.metaClass.printSize = { println delegate.size() } [1,2,3].printSize() //prints 3 

In Scala, you can use the implicit class :

 implicit class PrefixedString(val s: String) { def prefix = "prefix_" + s } "foo".prefix // returns "prefix_foo" 

Please look at this article.

An important note is that the Groovy / Scala source code is intended to be compiled into Java bytecode so that the resulting classes can be used in Java code.

+2
source

All Articles