user710818
user710818

Reputation: 24248

Java add new functions to library class

The problem: application uses some library. Like:

ClassA a=new ClassA();

In this library classA uses classB - e.g. call some method from classB. I need to change how this method works. Is it possible do without using AOP? Thanks.

Upvotes: 0

Views: 151

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298978

There are two options:

a) modify the source
b) modify the byte code

a) means: download the source, change it, build and use your own version. Drawback: for every new version of the library, you'll need to create a new patched version

b) For this, AOP (probably using AspectJ) is the easiest way. Other options would be to do it programmatically using commons / bcel or cglib. AOP is easier because you only have to implement the behaviour you want, whereas using byte code manipulation, you would also have to do lots of infrastructure programming (e.g. providing a custom ClassLoader or Java Agent that runs your patch).

Alternative c) is often the best: contact the developer of the library and ask him to provide the functionality you need.

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120198

You can subclass ClassA if ClassA is not final. You should probably download the source for the library and look at the internals to see how it works -- only create a subclass as a last resort -- you don't want to break the library.

Upvotes: 1

Related Questions