Can private methods of an abstract class be called using reflection?

Can private methods of an abstract class be called using reflection?

+3


source to share


3 answers


Yes, you can. You can use reflection. What you need -

  • A class object of an abstract class.
  • dynamically set the accessibility of the method to true. Check out 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

      

+3


source


You must instantiate concrete class

that the abstract class extends, or you must instantiate anonymous inner class instance

for the abstract class (and override methods marked abstract). Then you can use that instance and make the method available by making setAccessible(true)

. This will work if you don't mess up SecurityManager

(in most cases you won't). Then you can call the method



+1


source


Yes, you can.

but for this you need an object that is an instance of the abstract class.

0


source







All Articles