我有一个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();
}
}
每个对象都有一个称为“运行”的方法。我想调用该方法,但我不知道该怎么做。请问您能帮我吗? :)
答案 0 :(得分:3)
如果所有类都具有名为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();
}
}