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 ){}
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 ){}
Object ret = method.invoke(cla.newInstance(), null );
这两句的作用是干吗?
是否就可以直接用ret来使用类中的方法了?
是否只能实例化一个方法那我如果有多个方法该怎么办?
Method method = cla.getMethod("test", null); // 用invoke执行test方法,ret是返回值(如果test方法返回void,则ret==null)
Object ret = method.invoke(cla.newInstance(), null );
Method method = cla.getMethod("test",null);
Object ret = method.invoke(obj,null);
obj是你要引用的CLASS对象,然后你就可以用ret.methodname调用其他的方法了。
import class.a;
那么
Class.forName()的className为什么?
Object ret = method.invoke(cla.newInstance(), null );
返回值为String时该如何得到这个值?
Method method = cla.getMethod("test", null);
那不是要写很多吗?
Method []methods = cla.getMethods("test");
然后根据参数调用
一般步骤是,首先声明你所要调用方法的参数的类类型数组
如果你的方法要使用一个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);就可以了
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)); }