public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld");
}
private void prt(String msg){
System.out.println(msg);
}
}
调用mainҎ如下Q?br /> public class HelloWorldRefection {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
Method method = HelloWorld.class.getMethod("main",String[].class);
method.invoke(null,(Object)new String[]{});
}
}
调用privateҎ如下:
public class HelloWorldRefection {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
Class clazz = HelloWorld.class;
HelloWorld helloworld = HelloWorld.class.newInstance();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
if(method.getName().equals("prt")){
method.setAccessible(true);
method.invoke(helloworld, "hello");
}
}
}
}
ȝ:
1 调用mainҎ需要注意,mainҎ的参CؓString[]Q但是在method.invokeӞ需要将String[]强制转换为ObjectQ至于原因,|上很多说这个,? 要是说jdk执行mainҎ时要String[]分成多个参数{等。后l我分析了源代码后,会将q个问题专门写个文章出来?br /> 2 调用privateҎ需要注意,在调用此Ҏ之前Q需要将此执行的Ҏ讄以下Q而不是随便找个地方运行下method.setAccessible(true)完事了?br /> 3 使用反射动态调用方法时Q主要是用method.invoke()ҎQ如果是静态方法,则invoke的第一个参数设|nullQ如果不是静态方法,则将W一个参数设 |ؓ该类生成的对象即可?img src ="http://www.aygfsteel.com/morgan/aggbug/387590.html" width = "1" height = "1" />
]]>