1

We have a situation where we are using some library and we would like to customize the logic of a tiny private method used in the library. Unfortunately, the library isn't well written to be extended.

So basically, imagine if we have a library with the class ClassA like this one:

public class ClassA {

    public String buildMessage(){
        return "Hello, "+ buildSuffixString();
    }

    private String buildSuffixString(){
        return "World!";
    }
}

The class ClassA is used in the library by the class ClassB. ClassB is used in the library by ClassC and so on. ClassB creates its dependency in the constructor with the code like classA = new ClassA(); (Unfortunatelly). ClassC creates its dependency in the constructor with the code like classB = new ClassB();. And so on.

We would like to force everyone who uses a method buildMessage() of ClassA to obtain Hello, Kitty! message instead of Hello, World! (i.e. we need to replace an implementation of the private method buildSuffixString() to our own implementation). Is there a way to change a logic of a private method by using reflection or Java compiler or something else?

Oleksandr
  • 3,574
  • 8
  • 41
  • 78
  • 2
    [Apache Commons BCEL](https://commons.apache.org/proper/commons-bcel/). – Elliott Frisch Dec 14 '18 at 23:57
  • @ElliottFrisch Thank you a lot for the comment! I didn't know about this library. Do you have some example on how can we use this library to change the above code of the `buildSuffixString` method? – Oleksandr Dec 15 '18 at 00:04
  • Quick Google foind: CDI Dependency Injection as part of Java EE – Poohl Dec 15 '18 at 00:06

0 Answers0