How to call a private method from outside a java class

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

    Example of accessing private method(with parameter) using java reflection as follows :

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    class Test
    {
        private void call(int n)  //private method
        {
            System.out.println("in call()  n: "+ n);
        }
    }
    public class Sample
    {
        public static void main(String args[]) throws ClassNotFoundException,   NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
        {
            Class c=Class.forName("Test");  //specify class name in quotes
            Object obj=c.newInstance();
    
            //----Accessing private Method
            Method m=c.getDeclaredMethod("call",new Class[]{int.class}); //getting method with parameters
            m.setAccessible(true);
            m.invoke(obj,7);
        }
    }
    
    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
  • 2020-12-01 04:23

    If you want to pass any parameter to private function you can pass it as second, third..... arguments of invoke function. Following is sample code.

    Method meth = obj.getClass().getDeclaredMethod("getMyName", String.class);
    meth.setAccessible(true);
    String name = (String) meth.invoke(obj, "Green Goblin");
    

    Full example you can see Here

    0 讨论(0)
  • 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());
    
    0 讨论(0)
  • 2020-12-01 04:32
    method = object.getClass().getDeclaredMethod(methodName);
    method.setAccessible(true);
    method.invoke(object);
    
    0 讨论(0)
提交回复
热议问题