使用Java动态类加载 [英] Dynamic class loading with Java
本文介绍了使用Java动态类加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在这个具体的类中调用一个方法,也就是我需要设置:
MyInterface myclass = new concreteClassName();
myclass.function();
我该如何实现?
解决方案
String str =Test $ B ; //你的全名,而不是Test
$ b一个clazz = null; //更改A为界面
try {
clazz =(A)Class.forName(str).newInstance(); //更改A为界面
} catch(Exception e){
// TODO:handle exceptions
e.printStackTrace();
}
if(clazz!= null){
clazz.foo();
}
I want to dynamically load a concrete class which implements an interface. Input: concrete class name.
I need to call a method in this concrete class, that is, I'll need to set:
MyInterface myclass = new concreteClassName();
myclass.function();
How can I achieve this?
解决方案
have a look at Class.forName(String)
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();
}
这篇关于使用Java动态类加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文