簡體   English   中英

在Hashmap中傳遞class以及如何使用key獲取值

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

我正在嘗試將 class 作為 hashmap 中的值傳遞。我需要使用特定鍵獲取類(值)並為檢索到的 class 實例化 object。但是為了創建 object,我需要傳遞參數。

當我從另一個傳遞鍵值的 class 調用 getExpo 方法時,我的流程就到這里了。 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.

此過程的目的是在將來,我需要添加另一個鍵,對值,我不應該做任何更改.......所有 class 的實現都是相同的,即創建 object

我的 class 在這里

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

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM