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());
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()
,则让所有类实现Runnable
,然后将Map
value 声明为 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();
}
}
推荐阅读
- swift - SwiftUI:查看为属性
- swift - handleOpenURL,第二个参数(sourceApplication)使用什么值?
- php - 为什么 php ldap_search 在同一个查询中返回不同的属性?
- python - 有没有办法从日历js中提取数据(也许)?python beautifulsoup selenium post 日历抓取
- javascript - 单击时获取具有自己的迭代按钮的输入值
- javascript - Angular 7 - 布尔值总是计算为真
- apache-kafka - 扩展 Kafka:如何动态添加新的事件处理能力?
- postgresql - DB2 命令更改为 Postgres 命令
- sockets - 如何在 Rust 中将 SocketAddr 转换为字符串?
- c# - 在不使用 IDENTITY 的情况下在我的控制器中增加 id(编号)