我可以按字符串名称引用类吗?

时间:2015-12-04 06:18:27

标签: java class-reference

我有一个源自以下内容的实用程序列表:

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());
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用反射:

String name = "WordLength";
String className = hashMap.get(name);

Callable plugin = (Callable) Class.forName(className).newInstance();

使用HashMap存储className和字符串标识符

之间的绑定