通过反射调用父类的私有方法

使用反射可以看出子类是继承了父类的私有方法的(不管是否是final),只是直接调用父类的私有方法是不可以的,但是利用反射的方式可以调用。字段同理。

 
package work.litao;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
class Parent{
    Parent() {
        System.out.println("调用父类构造方法!");
    }
    private static void staticParent() {
        System.out.println("调用父类静态方法");
    }
    private final  void finalParent() {
        System.out.println("调用父类final方法");
    }
    private void printParent(){
        System.out.println("调用父类私有方法");
    }
}
class Child extends Parent {
    public void printChild(){
        System.out.println("调用子类公有方法");
    }
}
public class Test {
    public static void main(String[] args) throws Exception {
        //获取子类
        Class clazz = Class.forName("work.litao.Child");
        //得到父类
        Class superClass = clazz.getSuperclass();
        //得到父类非继承的所以方法
        Method[] methods = superClass.getDeclaredMethods();
        //设置私有方法可以被访问
        AccessibleObject.setAccessible(methods,true);
        for (Method m:methods) {
            System.out.println();
            System.out.println("子类调用方法"+m.getName()+"()的调用结果:" );
            m.invoke(new Child());
        }

    }
}

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.   [子类从其父类继承所有成员(字段,方法和嵌套类)。 构造函数不是成员,所以它们不被子类继承,但是可以从子类调用超类的构造函数。]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值