Creating an extension to a class?
-
13-03-2021 - |
Pregunta
In some languages like C# and Objective C, you can create class extensions. That means you can add additional methods to an existing class without having to extend that class. Is this possible in Java?
Solución
As Oli mentions, it is not possible.
It is worth mentioning that an extension method in C# is just a fancy way of calling an Static method, so although it looks like
someobject.MyExtensionMethod();
then the compiler translates that to
SomeStaticClass.MyExtensionMethod(someobject);
You are not really adding a method to the object
Otros consejos
No, not with standard Java.
You could use AspectJ that is using compile-time weaving to add to the bytecode.
I'm not aware of a language construct, that would allow you to do that, but you could use Decorator pattern to achieve your goal.
This is possible with the lombok library. There is an annotation that is called @ExtensionMethod.
This gives you that functionality.
See https://projectlombok.org/features/experimental/ExtensionMethod.html