Passing class in Hashmap and how to get the value using key

Go To StackoverFlow.com

1

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;
    }
}
2012-04-04 17:14
by Jessie


3

Try

Class aClass = hmap.get(key);
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
return (Predicate) constructor.newInstance(expression);
2012-04-04 17:40
by Luca
Thank you for your reply.......when i implement it in the getEcho method....Class aClass = hmap.get(key); am getting error in hmap since I am implemented hashmap in Static block, i cant able to access it - Jessie 2012-04-04 19:17
I need another help....... for some classes, I need to pass two arguments eg: (string,class type) eg:(expression,Boolean.class), how to implement it? and how to choose which constructor to execute...one class have one argument only with string.......another class have two arguments String and ClassJessie 2012-04-04 19:22
http://java.sun.com/developer/technicalArticles/ALT/Reflection - Luca 2012-04-05 06:27
Ads