Does Java support Swift-like class extensions?

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.


It can be done in other languages for JVM, like 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 implicit class:

implicit class PrefixedString(val s: String) {
   def prefix = "prefix_" + s 
}

"foo".prefix // returns "prefix_foo"

Please have a look at this article.

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


The Decorator Pattern is perhaps the closest match. It uses interface to maintain the type compatibility and composition to enhance the existing class' function. It's not the same principle as the one you're describing but might serve the same purpose.