我有一个源自以下内容的实用程序列表:
abstract public class BaseUtil implements Callable{
public String name;
public StreamWrapper data;
public void setData(StreamWrapper stream){ this.data = stream; }
private static Class me = BaseUtil.class;
private static Method[] availableUtilities = me.getDeclaredMethods();
public static Method[] getUtilities(){ return availableUtilities; }
}
我想在每个节点上都能够为它分配一个实用程序,例如:
Initialize(String utilName){
activeUtility = utilName;
gk = new GateKeeper(BaseUtil.getUtilities() <something>);
}
public class GateKeeper {
GateKeeper(BaseUtil util) {
this.util = util;
}
private BaseUtil util;
但我不确定如何从传入的String中获取特定的实用程序类。示例实用程序是:
public class WordLengthUtil extends BaseUtil {
private String name = "WordLength";
public Integer call() {
System.out.println(this.data);
return Integer.valueOf(this.data.length());
}
}
答案 0 :(得分:2)
您可以使用反射:
String name = "WordLength";
String className = hashMap.get(name);
Callable plugin = (Callable) Class.forName(className).newInstance();
使用HashMap存储className和字符串标识符
之间的绑定