用反射可以实现在b中动态的调用传进来的String1.你得知道传进来的String这个方法名是哪个类的2.用Class.forName()动态的加载这个类3.第二步返回一个Class类的实现:假设为:xxx4.xxx.getDeclaredMethod(String name, Class[] parameterTypes) 5.第4步返回一个Method对象:假设为mmm6.mmm.invoke(Object obj, Object[] args)就可以调用了
调试欢乐多
void print(String s){
System.out.println("This is in the class of Demo");
System.out.println(s);
}
}public class DynamicInvoke{
public static void invokedByArgs(String methodName)
throws NoSuchMethodException,
IllegalAccessException,
InvocationTargetException{
Method m = Demo.class.getDeclaredMethod
(methodName, new Class[]{String.class});
m.invoke(new Demo(), new Object[]{"invoked by Demo"});
}
public static void main(String[] args){
try{
invokedByArgs("print");
}catch(NoSuchMethodException e){
System.err.println("No Such Method");
}catch(IllegalAccessException e){
System.err.println("Illegal Access");
}catch(InvocationTargetException e){
System.err.println("Invocation Target");
}
}
}
wenchaohu213(夏吾),可以运行的,结贴
m.invoke(new Demo(), new Object[]{"invoked by Demo"});
这里怎样改?谢谢.