java - 如何实现一个以字符串为键和值的 HashMap ,它是一个要执行的函数

标签 java hashmap

我需要一个逻辑来更改以下源,以便

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  

可以这样做吗?
如果是,请给我一些关于如何实现这一点的指示?

谢谢。

最佳答案

使用RunnableCallable或任何其他接口(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/

相关文章:

Java Matcher 组输出问题

Java 框架...不关注 JTextField

java - 什么是java中的哈希函数?

java - 使用哈希码比较 Map 的关键元素

jquery - 如何在 javascript 中构建哈希并将其发布到服务器

android - arraylist<hashmap<string,string>> 不工作

java - 使用 put 存储新的键值对时,现有键的 HashMap 值会被覆盖。如何预防?

java - 如果两者都需要在同一类中的每个 @Test 中运行,如何使用多个凭据验证登录功能[在 Maven POM Selenium 项目中]

java - 使用我的程序逻辑时获得空输出

java - BouncyCaSTLe 是如何生成 ECDH "Keys"的?