我需要一个逻辑来改变以下来源
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"," PhoneNumber",..等。作为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
是否可以这样做?
如果是,请给我一些指导如何实现这一点?
感谢。
答案 0 :(得分: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 lambdas,代码不那么冗长:
map.put("Title", () -> object.setTitle(getString(attributes, VALUE_ATTR)));
答案 1 :(得分:0)
在java 1.5+中,这可以通过枚举来解决(看看TimeUnit)。但你说的是1.4。因此,您可以引入Attribute接口而不是name&功能和操纵:
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)