How to call a private method from outside a java class

后端 未结 5 1371
北海茫月
北海茫月 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);
        }
    }
    

提交回复
热议问题