我想动态加载一个实现接口的具体类。输入:具体类名。
我需要调用这个具体类中的方法,也就是说,我需要设置:
MyInterface myclass = new concreteClassName();
myclass.function();
我怎样才能实现这个目标?
看一下类名(字符串) http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName%28java.lang.String%29
String str = "Test$B"; //your full class name here instead of Test$B
A clazz = null; //change A to be your interface
try {
clazz = (A)Class.forName(str).newInstance(); //change A to be your interface
} catch (Exception e) {
//TODO: handle exceptions
e.printStackTrace();
}
if (clazz != null) {
clazz.foo();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)