How to call a private method from outside a java class

后端 未结 5 1363
北海茫月
北海茫月 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:21

    use setAccessible(true) on your Method object before using its invoke method.

    import java.lang.reflect.*;
    class Dummy{
        private void foo(){
            System.out.println("hello foo()");
        }
    }
    
    class Test{
        public static void main(String[] args) throws Exception {
            Dummy d = new Dummy();
            Method m = Dummy.class.getDeclaredMethod("foo");
            //m.invoke(d);// throws java.lang.IllegalAccessException
            m.setAccessible(true);// Abracadabra 
            m.invoke(d);// now its OK
        }
    }
    

提交回复
热议问题