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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With