Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to C# extension methods

Java does not support extension methods.

Instead, you can make a regular static method, or write your own class.


Extension methods are not just static method and not just convenience syntax sugar, in fact they are quite powerful tool. The main thing there is ability to override different methods based on different generic’s parameters instantiation. This is similar to Haskell’s type classes, and in fact, it looks like they are in C# to support C#’s Monads (i.e. LINQ). Even dropping LINQ syntax, I still don’t know any way to implement similar interfaces in Java.

And I don’t think it is possible to implement them in Java, because of Java’s type erasure semantics of generics parameters.


Project Lombok provides an annotation @ExtensionMethod that can be used to achieve the functionality you are asking for.


Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.

package extensions.java.lang.String;

import manifold.ext.api.*;

@Extension
public class MyStringExtension {

  public static void print(@This String thiz) {
    System.out.println(thiz);
  }

  @Extension
  public static String lineSeparator() {
    return System.lineSeparator();
  }
}

Manifold provides Java with C#-style extension methods and several other features. Unlike other tools, Manifold has no limitations and does not suffer from issues with generics, lambdas, IDE etc. Manifold provides several other features such as F#-style custom types, TypeScript-style structural interfaces, and Javascript-style expando types.

Additionally, IntelliJ provides comprehensive support for Manifold via the Manifold plugin.

Manifold is an open source project available on github.


The XTend language — which is a super-set of Java, and compiles to Java source code1 — supports this.