如何从子进程调用父私有方法? [英] How to invoke parent private method from child?

查看:116
本文介绍了如何从子进程调用父私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()
    }
}

你能否告诉我是否有可能通过java中的反射来做什么?

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

推荐答案

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();
        }
    }
}

这篇关于如何从子进程调用父私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆