Reputation: 77626
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?
Upvotes: 2
Views: 3933
Reputation: 31
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
Upvotes: 0
Reputation: 1492
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.
Upvotes: 1
Reputation: 21401
You could use AspectJ that is using compile-time weaving to add to the bytecode.
Upvotes: 1
Reputation: 8008
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
Upvotes: 9