简体   繁体   中英

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 . 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 :

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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