Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JAR Method Overriding

Tags:

java

So I'm new to Java and would really like some suggestions here.

I have a jar XYZ.jar which I've added to my classpath. This XYZ.jar has some 4 classes namely A,B,C,D. There is a method in CLASS D namely private void METHOD P() which is being called by CLASSES A,B,C.

Now I have a class Main.java in my project which is having a method METHOD R().

Now I would like to override private void METHOD P() with METHOD R() present in my Main.java. One thing I can do is that, I can extend my Main class with CLASS D. But, I would then have to modify the methodnames in CLASSES A,B,C which I don't want to do as the said classes are inside the jar.

So, what I would like to know is whether there's a way to override a private method of a class present inside a jar without making any changes to the rest of the classes calling the method, present inside the jar.

like image 891
Phillip Avatar asked Mar 18 '26 18:03

Phillip


1 Answers

Assuming your classes A, B and C expect a class D as their construction parameter:

class Main extends D {
    public static void Main(String[] args) {
        Main main = new Main();
        A a = new A(main);
        B b = new B(main);
        C c = new C(main);
    }

    public void R() { ... }

    public void P() {
        R();
    }
}

But this only works if D and it's method P() are not final, and your other classes don't instantiate D themself.

Another but expensive way would be to use PowerMockito to mock your method D.P() to use your Main.R(). But this shouldn't be used for production code

like image 191
Lino Avatar answered Mar 20 '26 08:03

Lino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!