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