Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从HashMap调用方法?_Java_Hashmap - Fatal编程技术网

Java 如何从HashMap调用方法?

Java 如何从HashMap调用方法?,java,hashmap,Java,Hashmap,我有一个HashMap,看起来是这样的: hmap = new HashMap<String, Object>(); // All list of exercises hmap.put("ArrayVerrification", new ArrayVerification()); hmap.put("DivideNumber", new DivideNumber()); hmap.put("Hello", new Hello());

我有一个HashMap,看起来是这样的:

     hmap = new HashMap<String, Object>();

    // All list of exercises
    hmap.put("ArrayVerrification", new ArrayVerification());
    hmap.put("DivideNumber", new DivideNumber());
    hmap.put("Hello", new Hello());
    hmap.put("Rectangle", new Rectangle());
    hmap.put("StringOperations", new StringOperations());
    hmap.put("Substring", new Substring());
    hmap.put("SumOfPrimeNumbers", new SumOfPrimeNumbers());
    hmap.put("Test", new Test());

    for (Map.Entry<String, Object> pair : hmap.entrySet()){
         if(pair.getKey().equals(extractClassNameFromComand)) {
              // this I want to do something like that
              // eg : Hello hello = new Hello;
              //      hello.run();
        }
    }

每个对象都有一个名为run的方法。我想调用那个方法,但我不知道怎么做。你能帮我吗

如果所有类都有一个名为run的no-arg方法,则实现所有类,然后将Map值声明为可运行:


你有HashMap吗?是的,我尝试了,但我在以下位置收到一个错误:hmap.putarrayVerification,new ArrayVerification;我认为语法一定不同。你所有的类都实现了runnable吗?@Alexandra你得到了什么错误?你怎么申报地图的?如果你提供一个,可能只有一个或两个这样的类,这会有所帮助。你自相矛盾。代码中的映射使用Object,而不是Runnable!
Map<String, Runnable> hmap = new HashMap<>();
// code to fill map here

for (Map.Entry<String, Runnable> pair : hmap.entrySet()){
    if (pair.getKey().equals(extractClassNameFromComand)) {
        pair.getValue().run();
    }
}
Map<String, Supplier<Runnable>> hmap = new HashMap<>();
hmap.put("ArrayVerrification", ArrayVerification::new);
hmap.put("DivideNumber", DivideNumber::new);
hmap.put("Hello", Hello::new);
hmap.put("Rectangle", Rectangle::new);
hmap.put("StringOperations", StringOperations::new);
hmap.put("Substring", Substring::new);
hmap.put("SumOfPrimeNumbers", SumOfPrimeNumbers::new);
hmap.put("Test", Test::new);

for (Map.Entry<String, Supplier<Runnable>> pair : hmap.entrySet()){
    if (pair.getKey().equals(extractClassNameFromComand)) {
        Supplier<Runnable> supplier = pair.getValue();
        Runnable obj = supplier.get(); // calls: new Xxx()
        obj.run();
    }
}