Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke parent private method from child? [duplicate]

public class A{
    private int getC(){
        return 0;
    }
}

public class B extends A{
    public static void main(String args[]){
        B = new B();
        //here I need to invoke getC()
    }
}

Can you please tell me if it is possible to do sush thing via reflection in java?

like image 556
dmreshet Avatar asked Jan 18 '13 11:01

dmreshet


2 Answers

class A{
    
    private void a(){
        System.out.println("private of A called");
    }
}

class B extends A{
    
    public void callAa(){
        try {
            System.out.println(Arrays.toString(getClass().getSuperclass().getMethods()));
            Method m = getClass().getSuperclass().getDeclaredMethod("a", new Class<?>[]{});
            m.setAccessible(true);
            m.invoke(this, (Object[])null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

EDIT: This is quiet an old post but adding a few nuggets of advice

Reconsider your design

Calling private method of parent, though possible through Reflection, but should not be done. Calling private methods on parent might leave the class in invalid state and may lead to unexpected behaviors.

like image 75
Narendra Pathai Avatar answered Oct 02 '22 13:10

Narendra Pathai


You can do it using reflection, but unless there is a very good reason to do so, you should first reconsider your design.

The code below prints 123, even when called from outside A.

public static void main(String[] args) throws Exception {
    Method m = A.class.getDeclaredMethod("getC");
    m.setAccessible(true); //bypasses the private modifier
    int i = (Integer) m.invoke(new A());
    System.out.println("i = " + i); //prints 123
}

public static class A {

    private int getC() {
        return 123;
    }
}
like image 28
assylias Avatar answered Oct 02 '22 13:10

assylias