问题是:在构造函数中初始化 VTDGen、VTDNav 或 AutoPilot 后,在其他方法中它们引用 null 并引发相应的异常。
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
为什么 autoPilot 引用 null?