用反射可以实现在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)就可以调用了

解决方案 »

  1.   

    import java.lang.reflect.*;class Demo{
    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");
         }    
        }
    }
      

  2.   

    谢谢fog628(发粪涂墙),
    wenchaohu213(夏吾),可以运行的,结贴
      

  3.   

    还想问一下,如果是多个参数怎么办?sorry.
    m.invoke(new Demo(), new Object[]{"invoked by Demo"});
    这里怎样改?谢谢.
      

  4.   

    m.invoke(new Demo(), new Object[]{"invoked by Demo"});这里的第二个参数是一个Object[], 它所存放的东西就是此函数调用时所要的参数,如是多个:new Object[]{"invoked by Demo", new Integer(10), new .....}