0

I have a list of utilities that derive from:

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

I want to, at each node, be able to assign a utility to it, something like:

Initialize(String utilName){
    activeUtility = utilName;
    gk = new GateKeeper(BaseUtil.getUtilities() <something>);
}

public class GateKeeper {
  GateKeeper(BaseUtil util) {
    this.util = util;
}

private BaseUtil util;

But I'm unsure on how to get the specific utility class from just the String passed in. An example utility is:

public class WordLengthUtil extends BaseUtil {
    private String name = "WordLength";
    public Integer call() {
        System.out.println(this.data);
        return Integer.valueOf(this.data.length());
    }
}
MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • You cannot directly do it. However, on the basis of Strings passed you can build different objects using the factory pattern. – Vivek Singh Dec 04 '15 at 06:20

1 Answers1

2

You can use reflection:

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

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

use HashMap to store binding between className and string identifier

Eldar Budagov
  • 312
  • 2
  • 11