I am trying pass class as value in hashmap. I need to get the class(value) using particular key and instantiate an object for the retrieved class. but in order to create object, i need to pass parameters.
My flow goes here, when i call the getExpo method from another class passing the key value. using the key value, i need to get the correct class and using that class need to instantiate the object and need to return the object. Inorder to create object, i need to pass the arguments since the class doesnot have default constructors.
The purpose of this procedure is in future, i need to add another key ,pair value, i shouldnot do any change........the implementation is same for all class ie creating the object
My class goes here
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;
}
}
Try
Class aClass = hmap.get(key);
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
return (Predicate) constructor.newInstance(expression);