你是要这样吗?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的组合是没问题的, 不过其他的好像不可以。
另一个办法, 有前提的
如果要调用的class们有相同的method, 如public static void print(), 一般来说这些class都是某一个parent class的children,
并且这些class的总数不多, 可以如下办
设class们是 Child1, Child2, Child3..., parent class is Parent, method是print,
Parent anObject = however_you_created_it;
if (anObject instanceof Child1)
Child1.print();
else if (anObject instanceof Child2)
Child2.print();
...
...
...
并且这些class的总数不多, 可以如下办
设class们是 Child1, Child2, Child3..., parent class is Parent, method是print,
Parent anObject = however_you_created_it;
if (anObject instanceof Child1)
Child1.print();
else if (anObject instanceof Child2)
Child2.print();
...
...
...