Alex Rivera | Logout

Can I override a private method in Java?

Asked 2012-05-16T17:49:36.780
14

I know I can use reflection to invoke a private method, and to get or set the value of a private variable, but I want to override a method.

public class SuperClass {

    public void printInt() {
        System.out.println("I am " + getClass() + ". The int is " + getInt());
    }

    private int getInt() {
        return 1;
    }
}

public class SubClass extends SuperClass {

    public static void main(String[] args) {
        (new SubClass()).printInt();
    }

    public int getInt() {
        return 2;
    }
}

I want the main method in SubClass to print out 2, but it prints out 1. I've heard this can be done through reflection, but I can't figure out how. If not reflection, does anyone know of another way of doing it? (Other than making SuperClass.getInt() protected, or copying and pasting the printInt() method into SubClass.) If actually overriding the private method is not possible, is there a way of placing some sort of trigger on it that will invoke a method in my sub-class either before or after the private method executes?

Edit
Report

2 Answers

5

I couldn't do this with reflection, but I have figured out a way to do it via instrumentation. I've used ASM, as suggested on Dhruba Bandopadhyay's blog. If you're interested, you can look at my code (there's too much to post it here).

answered 2012-05-27T17:49:52.293
-5

Read this carefully,

PRIVATE methods are NOT INHERITED... As they are not inherited, they CANNOT BE OVERRIDDEN

answered 2012-05-16T18:01:57.603

Your Answer