在Hashmap中传递类以及如何使用键获取值

时间:2012-04-04 17:14:40

标签: java reflection hashmap predicate

我正在尝试将类传递为hashmap中的值。我需要使用特定键获取类(值)并为检索到的类实例化一个对象。但是为了创建对象,我需要传递参数。

当我从另一个传递键值的类调用getExpo方法时,我的流程就在这里。使用键值,我需要获取正确的类,并使用该类需要实例化对象,并需要返回对象。为了创建对象,我需要传递参数,因为类没有默认的构造函数。

这个程序的目的是将来,我需要添加另一个键,对值,我不应该做任何改变........所有类的实现都是相同的,即创建对象

我上课到这里

public class ExampleFactory {

    static {
        HashMap<String,Class<?>> hmap = new HashMap<String,Class<?>>();

        hmap.put("jxpath", JXPathExpression.class);
        hmap.put("spel", SpelExpression.class);
    }

    public Predicate getExpo(String key,String expression) {

        // Need to get the class using key value and instantiate the object for the class
        // but i need to pass parameters in order to create the object.something like this

        //JXPathExpression object = new JXPathExpression(expression);
        return null;
    }
}

1 个答案:

答案 0 :(得分:3)

尝试

Class aClass = hmap.get(key);
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
return (Predicate) constructor.newInstance(expression);