首页 > 解决方案 > 如何从 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());
    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”的方法。我想调用该方法,但我不知道该怎么做。你能帮我吗?:)

标签: javahashmap

解决方案


如果所有类都调用了一个无参数方法run(),则让所有类实现Runnable,然后将Mapvalue 声明为 a 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();
    }
}

如果要将对象的构造推迟到循环内部,请使用Supplier

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

推荐阅读