Search code examples
javaclassextend

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.


Solution

  • 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.