Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflect/AOP override supertype private Method

Is it at all possible to "override" a private method of a super class in Java?

The class whose method I wish to override is a third party class so I cannot modify the source. It would be ideal if there were some way to reflectively set a method on a class.

Alternatively, if it is possible to intercept a private method of a third party class then this would be suitable.

like image 486
Finbarr Avatar asked Sep 19 '25 03:09

Finbarr


2 Answers

YES. You can do it with AspectJ. It is not a true override but result will be so.

Here your super class;

public class MySuperClass {

    private void content(String text) {
       System.out.print("I'm super " + text);
    }
    
    public void echo() {
       content("!");
    }        
}

Create an interface which contains similar method;

public interface Content {
    void safeContent(String text);
}

Create an aspect that forces super class to implement that interface and add an around adviser to call it.

public privileged aspect SuperClassAspect {

    void around(MySuperClass obj)
            : execution(* content(String)) && target(obj) {

        Object[] args = thisJoinPoint.getArgs();
        ((Content) obj).safeContent((String) args[0]);
    }

    // compiler requires
    public void MySuperClass.safeContent(String text) {}


    declare parents :MySuperClass implements Content;
}

Create your child class that extends super and implements that interface.

public class Overrider extends MySuperClass implements Content {

    public void safeContent(String text) {
        System.out.print("Not that super " + text);
    }
}

Now if you construct a Overrider object and invoke echo method, you will have an output of Overriders safeContent's method.

like image 123
Ferhat Sobay Avatar answered Sep 20 '25 18:09

Ferhat Sobay


Is it at all possible to "override" a private method of a super class in Java?

No

I don't think using Reflection there would be a tweak , it will break OOP there

like image 31
jmj Avatar answered Sep 20 '25 17:09

jmj