aryaxt
aryaxt

Reputation: 77626

Creating an extension to a class?

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

Answers (5)

Basilios Raptis
Basilios Raptis

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

Tomáš Plešek
Tomáš Plešek

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

dimitrisli
dimitrisli

Reputation: 21401

You could use AspectJ that is using compile-time weaving to add to the bytecode.

Upvotes: 1

Sebastian Piu
Sebastian Piu

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

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

No, not with standard Java.

Upvotes: 3

Related Questions