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.
You do not have a legal way to do this. But I can suggest you the following solutions.
protected
instead ofprivate
. Now write your subclass and compile it against your stub. Then package only your subclass and try to run it with the "real" class. It should work. I have not tried this trick with inheritance but I have tried it when I had to access private method or field and it worked fine for me.YES. You can do it with aspectj. It is not a true override but result will be so.
Here your super class;
Create an interface which contains similar method;
Create an aspect that forces super class to implement that interface and add an around adviser to call it.
Create your child class that extends super and implements that interface.
Now if you construct a Overrider object and invoke echo method, you will have an output of Overriders safeContent's method.
No
I don't think using Reflection there would be a tweak , it will break
OOP
thereyes it's possible ,but you should not do it, because it contradicts one of the SOLID principles. More exactly it contradicts Liskov substitution principle.
So in other words , private method is property of object, so your object of inherited type must have the same property. The same with throws for methods.
Java restricts it because of it.