如何从java类外部调用私有方法
我有一个Dummy
类,它有一个名为sayHello
的私有方法。 我想从Dummy
外面打电话给sayHello
。 我认为它应该可以reflection,但我得到一个IllegalAccessException
。 有任何想法吗???
在使用其invoke
方法之前,在Method对象上使用setAccessible(true)
。
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 } }
首先,您必须获得类,这是非常简单的,然后使用getDeclaredMethod
按名称获取方法,然后您需要将方法设置为可由Method
对象上的setAccessible
方法访问。
Class> clazz = Class.forName("test.Dummy"); Method m = clazz.getDeclaredMethod("sayHello"); m.setAccessible(true); m.invoke(new Dummy());
method = object.getClass().getDeclaredMethod(methodName); method.setAccessible(true); method.invoke(object);
如果要将任何参数传递给私有函数,可以将其作为调用函数的第二个,第三个…..参数传递。 以下是示例代码。
Method meth = obj.getClass().getDeclaredMethod("getMyName", String.class); meth.setAccessible(true); String name = (String) meth.invoke(obj, "Green Goblin");
完整的例子你可以看到这里
使用javareflection访问私有方法(带参数)的示例如下:
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); } }