简体   繁体   English

我们可以使用反射调用抽象类的私有方法吗?

[英]Can we call private methods of abstract class using reflection?

我们可以使用反射调用抽象类的私有方法吗?

Yes you can. 是的你可以。 You can use reflection . 你可以使用反射 What you need - 你需要什么 -

  1. The class object of Abstract Class. 抽象类的类对象。
  2. dynamically set the method's accessibility to true . 动态地将方法的可访问性设置为true Check the code below. 检查下面的代码。
class ExitPuzzle extends MyAbstractClass {
    public static void main(String... args) throws IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        Class clazz = MyAbstractClass.class;
        Method[] methods = clazz.getDeclaredMethods();
        System.out.println(Arrays.toString(methods));
        methods[0].setAccessible(true);
        methods[0].invoke(new ExitPuzzle(), null);
    }

}

abstract class MyAbstractClass {
    private void myMethod() {
        System.out.println("in MyAbstractClass");
    }
}

O/P : O / P:

[private void MyAbstractClass.myMethod()]
in MyAbstractClass

您应该创建一个扩展抽象类的concrete class的实例,或者您应该为抽象类创建一个anonymous inner class instance (并覆盖标记为abstract的方法)。然后您可以使用该实例并通过setAccessible(true)使该方法可访问setAccessible(true) 。除非你搞砸了SecurityManager (在大多数情况下你不会这样做),否则这会有效。然后你可以调用方法

yes you can. 是的你可以。

but you will need an object that is an instance of the abstract class for this. 但是你需要一个对象,它是一个抽象类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM