初始化NodeList Java

时间:2015-06-17 16:50:10

标签: java xml

我试图摆脱NodeList的null初始化,但它似乎没有出现:

NodeList compiledNodeLIst = new Nodelist();

当我尝试在try语句中移动它时,如下所示:

private NodeList compileToNodeList(String pattern, Document document){
            try{
                NodeList compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);

我的Return变量无法解析,如果我将其移入try块我的方法错误,没有return语句。以下是完整的陈述。

   private NodeList compileToNodeList(String pattern, Document document){
            NodeList compiledNodeList = null;
            try{
                compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);
            } catch (XPathExpressionException e){
                //TODO code for logging
                e.printStackTrace();
            }
            return compiledNodeList;

这在技术上是有效的,但我希望要么摆脱空或解释为什么这是不可能的。

2 个答案:

答案 0 :(得分:1)

你的方法

   private NodeList compileToNodeList(String pattern, Document document){
        NodeList compiledNodeList = null;
        try{
            compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);
        } catch (XPathExpressionException e){
            //TODO code for logging
            e.printStackTrace();
        }
        return compiledNodeList;
   }

几乎是的权利。 TODO语句告诉我你计划只记录错误。你确定这是预期的吗?您从底层库中收到错误,并且您不想告诉调用者它?如果这是真的,我可以删除这个"回答。"但如果没有,这是一个更好的选择

 private NodeList compileToNodeList(String pattern, Document document){
        NodeList compiledNodeList = null;
        try{
            compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);
        } catch (XPathExpressionException e){
            throw new IllegalStateException("Unable to create the compiled node list: " + e.getMessage(), e);
        }
        return compiledNodeList;
 } 

当您遇到意外状态时抛出异常是 正确 要做的事情。我显示的是RuntimeException类型,因为我只是如何滚动,但您也可以选择一些已检查Exception,但这意味着必须处理将其抛出链

捕获异常并创建新的EmptyNodeList也是可行的,假设可以(不让来电者知道有问题)。

答案 1 :(得分:0)

最好让此方法的调用者检查nodelist是否为null。

如果仍然必须具有非null返回值(如果发生异常),则可以创建NodeList的虚拟或匿名实现并返回:

public static final class EmptyNodeList implements NodeList{
//no op methods
}
private NodeList compileToNodeList(String pattern, Document document){
        NodeList compiledNodeList = null;
        try{
            compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);
        } catch (XPathExpressionException e){
            //TODO code for logging
            e.printStackTrace();
            compiledNodeList = new EmptyNodeList();
        }
        return compiledNodeList;
}

public static final NodeList emptyNodeList = new NodeList() {
    @Override
    public Node item(int index) {
        return null;
    }

    @Override
    public int getLength() {
        return 0;
    }
};