如何实现一个以字符串作为键和值的哈希图,它是一个要执行的函数

问题描述 投票:0回答:2

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

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”、“电话号码”等。作为哈希图中的键,值应该执行“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  

我该如何实现这个?

java hashmap
2个回答
2
投票

使用

Runnable
Callable
或任何其他接口或抽象类作为值类型:

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)));

0
投票

在 java 1.5+ 中,这可以通过枚举来解决(看看 TimeUnit)。但你说的是1.4。因此,您可以引入 Attribute 接口而不是名称和函数并使用它们进行操作:

interface Attribute {
    void apply(Object obj);
}
abstract class AttributeAdapter<T> implements Attribute {
    protected final T value;
    protected AttributeAdapter(T value) {
        this.value = value;
    }
    ... // Overrides equals/hashCode/toString
    public String toString() {
        return value == null ? 'null' : value.toString();
    }
}
class TitleAttribute extends AttributeAdapter<String> {
    TitleAttribute(String title) {
        super(title);
    }
    void apply(Object obj) {
        obj.setTitle(value);
    }
}

// And speed up your code:
setAttribute(attributes, ATTR, new TitleAttribute("Some title value"));
...
getAttribute(attributes, ATTR).apply(object)
© www.soinside.com 2019 - 2024. All rights reserved.