import java.lang.reflect.*;Stirng className = null;
 if(...)
   className = ...;
 else  if(..)
    className = ...;
 .... 
  try {      Class cla = Class.forName(className);
      Method method = cla.getMethod("test", null);
      Object ret = method.invoke(cla.newInstance(), null );  }catch(Exception e ){}

解决方案 »

  1.   

    具体的使用是如何?用Class.forName(); 后,class中的方法无法被引用到啊?
      

  2.   

    Method method = cla.getMethod("test", null);
          Object ret = method.invoke(cla.newInstance(), null );
    这两句的作用是干吗?
    是否就可以直接用ret来使用类中的方法了?
      

  3.   

    Method method = cla.getMethod("test", null);
    是否只能实例化一个方法那我如果有多个方法该怎么办?
      

  4.   

    // 得到test()方法的调用入口。
    Method method = cla.getMethod("test", null); // 用invoke执行test方法,ret是返回值(如果test方法返回void,则ret==null)
    Object ret = method.invoke(cla.newInstance(), null );
      

  5.   

    class testclass=new a();   //compile error. Why?
      

  6.   

    可以用 Class cla = obj.getClass();
           Method method = cla.getMethod("test",null);
           Object ret = method.invoke(obj,null);
    obj是你要引用的CLASS对象,然后你就可以用ret.methodname调用其他的方法了。
      

  7.   

    如果我在类中
    import class.a;
    那么
    Class.forName()的className为什么?
      

  8.   

    // 用invoke执行test方法,ret是返回值(如果test方法返回void,则ret==null)
    Object ret = method.invoke(cla.newInstance(), null );
    返回值为String时该如何得到这个值?
      

  9.   

    有多个方法的时候
    Method method = cla.getMethod("test", null);
    那不是要写很多吗?
      

  10.   

    如果方法名相同,可以这么做
    Method []methods = cla.getMethods("test");
    然后根据参数调用
      

  11.   

    Method的invoke就好比是c语言中获得方法的指针一样!
    一般步骤是,首先声明你所要调用方法的参数的类类型数组
    如果你的方法要使用一个int型数据作为参数,那么
    Class[] args={Integer.class};
    然后,使用classname加载该类Class myclass1 = Class.forName("aaa");
    接着Method mymethod1 = myclass1.getMethod("methodname",args);
    最后声明方法参数Object args2={new Integer(5)};
    mymethod1.invoke(myclass1.newInstance(),args2);就可以了
      

  12.   

    给我你的mail,我给你例子!~
      

  13.   

    这些类都继承同一个父类,重写test方法,然后将类名传递近来,调用
    applicationInstance()方法,返回值转换成父类实例,然后运行该实例
    的test方法public static Object applicationInstance(String className)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException {        return (applicationClass(className).newInstance());    }public static Class applicationClass(String className) throws ClassNotFoundException {        // Look up the class loader to be used
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                classLoader = this.class.getClassLoader();
            }        // Attempt to load the specified class
            return (classLoader.loadClass(className));    }