使用Java中的SAX最小化代码的重复

时间:2013-09-20 04:05:25

标签: sax saxparser

class Foo {
    String member1;
    String member2;
    // Getters and Setters
    ...
}

class XmlDao extends Default Handler{
    List<Foo> foos;
    Foo tempFoo;
    String tempValue;
    ...

    @Override
    public void characters(char[] ac, int i, int j) throws SAXException {
        tempValue = new String(ac, i, j);
    }

    @Override
    public void endElement(String s, String s1, String element) throws SAXException {
        ...
        if (element.equalsIgnoreCase("member1")) {
            tempFoo.setMember1(tmpValue);
        }
        if (element.equalsIgnoreCase("member2")) {
            tempFoo.setMember2(tmpValue);
        }
        ....
    }
}

这里的问题是,对于我添加到模型Foo的永远成员变量,我还必须进入DAO并添加

        if (element.equalsIgnoreCase("member1")) {
            tempFoo.setMember1(tmpValue);
        }

public void endElement。我意识到我可以switch但问题是相同的。处理这个问题的最佳方法是什么?理想情况下,我宁愿一次写一次。在搜索了这个问题之后,我遇到了Reflection。这允许我写两次,但在一个类中,而不是两个类:

在我的模型Foo中,我添加了以下静态方法:

public static Map<String, Method> getMap() throws NoSuchMethodException, SecurityException {
    Map<String, Method> map = new HashMap<String,Method>();
    map.put("member1", Foo.class.getMethod("setMember1", String.class));
    map.put("member2", Foo.class.getMethod("setMember2", String.class));
    return map;

}

在我的XmlDao中,我添加了Map<String, Method> map,并在其构造函数中调用了Foo.getMap()。我还删除了if方法中的switch / endElement语句,并将以下内容添加到该方法中:

for (Entry<String, Method> entry : map.entrySet()) {
    if (element.equalsIgnoreCase(entry.getKey())) {
        entry.getValue().invoke(tempFoo, tmpValue);
    }
}

所以这种方法有效,但我仍然觉得它不优雅。

1 个答案:

答案 0 :(得分:0)

为什么在解决方案中使用for?只是做:

if (map.containsKey(element)) {
    map.get(element).invoke(tempFoo, tmpValue);
}