問題是:在構造函數中初始化VTDGen,VTDNav或AutoPilot後,在其他方法中引用null,並引發相應的異常。VTD-XML:對象初始化後仍然引用空
public class Configuration {
public Configuration(String dir, String filename, ResourceBundle resourceBundle) throws IOException, IndexWriteException, IndexReadException {
String XMLFilename = filename + ".xml";
String indexFilename = filename + ".vxl";
vtdGen = new VTDGen();
vtdGen.parseFile("D:/Librarian/config/configuration.xml", true);
vtdNav = vtdGen.getNav();
autoPilot = new AutoPilot(vtdNav);
boolean gen = vtdGen!=null;
boolean nav = vtdNav!=null;
boolean pilot = autoPilot!= null;
System.out.println("VTDGEN - " + gen + "\n" + "VTDNAV - " + nav + "\n" + "AUTOPILOT - " + pilot + "\n");
}
public Configuration(ResourceBundle resourceBundle) {
try {
new Configuration(defaultDir, defaultFileName, resourceBundle);
} catch (IOException | IndexWriteException | IndexReadException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public ArrayList<String> stringValue(String xPathExpression) {
try {
boolean pilot = autoPilot != null;
System.out.println("AUTOPILOT - " + pilot + "\n" + "String.length = " + xPathExpression.length() + "\n" + "String = " + xPathExpression);
autoPilot.selectXPath(xPathExpression);
int i;
while ((i = autoPilot.evalXPath())!=-1) {
stringResult.add(vtdNav.toString(i));
}
} catch (XPathEvalException | NavException | XPathParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return stringResult;
}
public void writeIndex(File indexFile) {
try (FileOutputStream fos = new FileOutputStream(indexFile)){
if (parsed) {
vtdGen.writeIndex(fos);
}
} catch (IndexWriteException | IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public File createIndexFile(String dir, String filename){
indexFile = new File(dir + filename + ".vxl");
writeIndex(indexFile);
return indexFile;
}
private final String defaultDir = System.getProperty("user.dir") + "/config/";
private final String defaultFileName = "configuration";
private final String defaultXMLFile = defaultFileName + ".xml";
private final String defaultIndexFile = defaultFileName + ".vxl";
private boolean parsed;
private VTDGen vtdGen;
private VTDNav vtdNav;
private AutoPilot autoPilot;
private File indexFile;
private ArrayList<String> stringResult;
}
結果是:
VTDGEN - true
VTDNAV - true
AUTOPILOT - true
AUTOPILOT - false
String.length = 30
String = /configuration/lastMode/text()
例外:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.NullPointerException
at core.config.Configuration.stringValue(Configuration.java:45)
at UI.PrimaryStageController.test(PrimaryStageController.java:77)
... 57 more
爲什麼自動駕駛儀指空?
除了OP不能吞下異常,當然。 –
謝謝你,喬恩!我已經在此添加了一個註釋 – Tala