我需要一个逻辑来更改以下源,以便
if (getString(attributes, NAME_ATTR).equals("Title"))
{
object.setTitle(getString(attributes, VALUE_ATTR));
}
else if (getString(attributes, NAME_ATTR).equals("Id"))
{
object.setID(getString(attributes, VALUE_ATTR));
}
else if (getString(attributes, NAME_ATTR).equals("PhoneNumber"))
{
object.setPhoneNumber(getString(attributes, VALUE_ATTR));
}
else if (*)//lot of cases like this
{
object.set*(getString(attributes, VALUE_ATTR));
}
...
这需要使用 hashMap 来完成。
我想存储“标题”、“ID”、“电话号码”等。作为 HashMap 中的键,值应该执行“object.setTitle(getString(attributes, VALUE_ATTR))”功能。
Keys | Values
----------------------------
Title | object.setTitle(getString(attributes, VALUE_ATTR)) (should set the tilte field in the object)
|
Id | object.setId(getString(attributes, VALUE_ATTR)) (should set the id field in the object)
|
etc.. | should set the specific field in the object
可以这样做吗?
如果是,请给我一些关于如何实现这一点的指示?
谢谢。
最佳答案
使用Runnable
、Callable
或任何其他接口(interface)或抽象类作为值类型:
map.put("Title", new Runnable() {
@Override
public void run() {
object.setTitle(getString(attributes, VALUE_ATTR))
}
});
并使用它:
Runnable r = map.get("Title");
r.run();
使用 Java 8 lambda,代码就不再那么冗长:
map.put("Title", () -> object.setTitle(getString(attributes, VALUE_ATTR)));
关于java - 如何实现一个以字符串为键和值的 HashMap ,它是一个要执行的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204209/