我试图消除NodeList的空初始化,但似乎我做不到:
NodeList compiledNodeLIst = new Nodelist();当我尝试将它移到try语句中时,如下所示:
private NodeList compileToNodeList(String pattern, Document document){
try{
NodeList compiledNodeList = (NodeList) xPath.compile("/*/UserList/User").evaluate(document, XPathConstants.NODESET);我的返回变量不能被解析,如果我把它移到try中,就会阻塞我的方法错误而没有返回语句。以下是全文。
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;这在技术上是可行的,但我希望要么去掉null,要么解释一下为什么这是不可能的。
发布于 2015-06-17 17:11:59
你的方法
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也是可行的,前提是这是可以的(不让调用者知道存在问题)。
发布于 2015-06-17 17:04:05
最好让这个方法的调用者检查nodelist是否为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;
}
};https://stackoverflow.com/questions/30897704
复制相似问题