Ham*_*abi 28 java reflection private call
我有一个Dummy类,有一个私有方法调用sayHello.我想sayHello从外面打电话Dummy.我认为这应该是可能的反射,但我得到了IllegalAccessException.有任何想法吗???
Psh*_*emo 59
利用setAccessible(true)使用其之前的Method对象的invoke方法.
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
}
}
Run Code Online (Sandbox Code Playgroud)
首先你必须得到类,这是非常直接的,然后使用名称获取方法getDeclaredMethod然后你需要将方法设置为对象setAccessible上的方法可访问Method.
Class<?> clazz = Class.forName("test.Dummy");
Method m = clazz.getDeclaredMethod("sayHello");
m.setAccessible(true);
m.invoke(new Dummy());
Run Code Online (Sandbox Code Playgroud)
method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
method.invoke(object);
Run Code Online (Sandbox Code Playgroud)
小智 6
如果要将任何参数传递给私有函数,可以将其作为调用函数的第二个,第三个.....参数传递.以下是示例代码.
Method meth = obj.getClass().getDeclaredMethod("getMyName", String.class);
meth.setAccessible(true);
String name = (String) meth.invoke(obj, "Green Goblin");
Run Code Online (Sandbox Code Playgroud)
完整的例子你可以看到这里
使用java反射访问私有方法(带参数)的示例如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)