How to call a private method from outside a java class

后端 未结 5 1380
北海茫月
北海茫月 2020-12-01 03:33

I have a Dummy class that has a private method called sayHello. I want to call sayHello from outside Dummy. I think it sh

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 04:31

    First you gotta get the class, which is pretty straight forward, then get the method by name using getDeclaredMethod then you need to set the method as accessible by setAccessible method on the Method object.

        Class clazz = Class.forName("test.Dummy");
    
        Method m = clazz.getDeclaredMethod("sayHello");
    
        m.setAccessible(true);
    
        m.invoke(new Dummy());
    

提交回复
热议问题