【问题标题】:How to call a method from an HashMap?如何从 HashMap 调用方法?
【发布时间】:2018-08-22 18:30:54
【问题描述】:

我有一个 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”的方法。我想调用该方法,但我不知道该怎么做。你能帮我吗? :)

【问题讨论】:

  • 你有HashMap&lt;String, Runnable&gt;吗?
  • 是的,我尝试了,但我在以下位置收到错误:hmap.put("ArrayVerrification", new ArrayVerification());我认为语法一定不一样。
  • 你所有的类都实现了runnable吗?
  • @Alexandra 你得到什么错误?你是如何声明地图的?如果您提供 minimal reproducible example 会有所帮助,可能只有其中一两个类。
  • 你自相矛盾。代码中的地图使用 Object,而不是 Runnable!

标签: java hashmap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2021-07-09
    • 2011-05-27
    • 2021-12-21
    • 1970-01-01
    • 2023-03-27
    • 2022-09-23
    相关资源
    最近更新 更多