Sobes.tech
Junior

How would you write an extension method in Java?

sobes.tech AI

Answer from AI

In Java, it is impossible to write true extension methods in the same sense as in Kotlin or C#. The main reason is the lack of direct syntactic sugar for adding methods to existing classes while maintaining encapsulation principles.

However, similar behavior can be achieved using the following patterns:

  1. Helper static method: Create a static class with public static methods that accept an instance of the class you want to "extend."

    // Example class to be "extended"
    public class MyClass {
        private String name;
    
        public MyClass(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    }
    
    // Static class with "extension method"
    public class MyClassExtensions {
        // Method that mimics an extension method
        public static void printNameUpperCase(MyClass obj) {
            if (obj != null) {
                System.out.println(obj.getName().toUpperCase());
            }
        }
    }
    

    Usage:

    // Using the "extension method"
    MyClass myObj = new MyClass("test");
    MyClassExtensions.printNameUpperCase(myObj); // Call static method
    
  2. Decorator pattern (wrapper): Create a new class that wraps an existing class and adds new behavior.

    // Decorator class
    public class MyClassDecorator {
        private MyClass original; // Reference to the original object
    
        public MyClassDecorator(MyClass original) {
            this.original = original;
        }
    
        // Method that mimics an extension method
        public void printNameUpperCase() {
            if (original != null) {
                System.out.println(original.getName().toUpperCase());
            }
        }
    
        // Additional methods can delegate calls to the original object
        public String getName() {
            return original.getName();
        }
    }
    

    Usage:

    // Using the decorator
    MyClass myObj = new MyClass("another test");
    MyClassDecorator decoratedObj = new MyClassDecorator(myObj);
    decoratedObj.printNameUpperCase(); // Call decorator method
    
  3. Inheritance: If the class is not marked as final, you can create a subclass and add new methods. This is not an extension method in the strict sense, as you create a new type, but it is one way to add functionality.

    // Subclass with a new method
    public class ExtendedMyClass extends MyClass {
    
        public ExtendedMyClass(String name) {
            super(name);
        }
    
        // New method in subclass
        public void printNameUpperCase() {
            System.out.println(getName().toUpperCase());
        }
    }
    

    Usage (works only with instances of ExtendedMyClass):

    // Using the subclass
    ExtendedMyClass extendedObj = new ExtendedMyClass("inheritance test");
    extendedObj.printNameUpperCase(); // Call subclass method
    

The most common approach to mimic extension methods in Java, especially for adding utility functionality to existing library classes, is to use static helper methods. This approach is the closest in spirit to extension methods from other languages, although it requires calling via the static class name.