日期:2014-05-20  浏览次数:20691 次

大家帮忙看看这个面试题!
public class Test{

 public static void Temp(String ClassName,String MethodName,String args)

{

 .................................................

}

public static void main(String args[])

{

  Temp("Hello","Demo","nihao");

}

}

class Hello

{

  public void Demo(String args)

  {

  System.out.println("Hello"+args);

 }

}

写一个方法:public void Temp(String ClassName,String MethodName,String args),使得这个方法能够实现调用,其中ClassName为类名,MethodName为方法名,args参数。例如:Temp("Hello","Demo","nihao");


------解决方案--------------------
反射啊!自己看书去吧!
------解决方案--------------------
挺容易的
------解决方案--------------------
Java code

import java.lang.reflect.Method;

public class Test1 {

    public static void Temp(String ClassName, String MethodName, String args) throws Exception {
        
        Class c = Class.forName(ClassName);
        
        Method method = c.getDeclaredMethod(MethodName, String.class);
        
        Object obj = c.newInstance();
        
        method.invoke(obj, args);
    }

    public static void main(String args[]) throws Exception {

        Temp("Hello", "Demo", "nihao");

    }
}

class Hello {

    public void Demo(String args) {

        System.out.println("Hello" + args);

    }

}