你是要这样吗?File Name: Test.java
--------------------------------------------
import java.io.*;
import java.lang.reflect.Method;
public class Test
{
public static void main(String args[]) throws Exception
{
new Test(args[0], args[1]);
}
public Test (String className, String methodName) throws Exception
{
Class c = Class.forName(className);
Method m = c.getMethod(methodName, null);
m.invoke(this, null);
}
}
File Name: MyClass1.java
-----------------------------
public class MyClass1
{
public static void testMethod ()
{
System.out.println("My Name is MyClass1");
}
}
File Name: MyClass2.java
----------------------------
public class MyClass2
{
public static void testMethod ()
{
System.out.println("My Name is MyClass2");
}
}
以上code, 运行结果如下
>>java Test MyClass1 print
>>My Name is MyClass1
>>java Test MyClass2 print
>>My Name is MyClass2
不过这个里面的modifier和static keyword好像有要求, 以上public+static的组合是没问题的, 不过其他的好像不可以。
No, not necessary.
Java reflection can handle normal method calls using generic reflection mechanism.