Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default method to extend existing JDK interfaces

Tags:

java

java-8

Am I able to use default methods to extend existing JDK interfaces like List to add an extra method to anything that implements it?

If so, is there a simple example anywhere?

like image 795
Cheetah Avatar asked Jan 27 '26 05:01

Cheetah


2 Answers

The JDK code, as with any other piece of compiled code, cannot be modified. So, any existing type (List or other) cannot change its behavior via the addition of a method, or of any other mechanism.

The only option is to just extend the classes you want to modify (if they are not declared as final - e.g., String cannot be extended) and change the functionality there. Obviously, any extended class also has the type of all its parents so, for example, an ExtendedList class is also a List, assuming its declaration is something like

public class ExtendedList<E> extends List<E>
{
    ...
}

What you are asking is probably the functionality of Extension Methods, as already mentioned in a comment above, which is a rather cool feature not supported by Java. Other languages, such as C#, offer such support.

like image 71
PNS Avatar answered Jan 29 '26 20:01

PNS


You can make your own Extension Methods to add methods to JDK classes but not in Java but by using other JVM languages like Groovy.

here is a Groovy tutorial on how to add Extension methods

http://groovy.codehaus.org/Creating+an+extension+module

Basically, you just have to make a new class with a static method you want to add. The first parameter of this method is the object you want to add the method to and any other parameters are the parameters in your method

public class MyExtension{
     public static String myMethod(List list, /*  other params here*/){
              //do stuff

     }
}

Then you need to add a module descriptor file name org.codehaus.groovy.runtime.ExtensionModule into the META-INF/services directory with the following contents:

moduleName=your-module-name
moduleVersion=your-module-version
extensionClasses=your-extension-full-classname
staticExtensionClasses= other-extension-class-for-static-methods

And that's it

like image 20
dkatzel Avatar answered Jan 29 '26 19:01

dkatzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!