我正在尝试使用 Eclipse 的 AST 解析器作为独立的解析器来解析 Java 源文件。这是获取编译单元的一小段代码:
public CompilationUnit getCompilationUnit(ASTParser parser) {
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
return cu;
}
如果我尝试在没有 Eclipse IDE 的情况下独立执行此代码,则会收到以下错误:
java.lang.NoSuchFieldError: resources
at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2545) [org.eclipse.jdt.core_3.8.2.v20120814-155456.jar:]
at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:2423) [org.eclipse.jdt.core_3.8.2.v20120814-155456.jar:]
at org.eclipse.jdt.core.dom.ASTConverter.convert(ASTConverter.java:534) [org.eclipse.jdt.core_3.8.2.v20120814-155456.jar:]
我不明白它从哪里调用方法resources
。如果我尝试从 Eclipse IDE 运行,它可以正常工作,没有任何问题。我已在类路径中包含以下 JAR 文件:
org.eclipse.core.contenttype_3.4.200.v20120523-2004.jar
org.eclipse.core.jobs_3.5.300.v20120912-155018.jar
org.eclipse.core.resources_3.8.1.v20121114-124432.jar
org.eclipse.core.runtime_3.8.0.v20120912-155025.jar
org.eclipse.equinox.common_3.6.100.v20120522-1841.jar
org.eclipse.equinox.preferences_3.5.1.v20121031-182809.jar
org.eclipse.jdt.core_3.8.3.v20130121-145325.jar
org.eclipse.osgi_3.8.2.v20130124-134944.jar
我已经包含了成功运行所需的所有 jar 文件。但是当我运行时出现这个错误。有人可以指导我吗?
最佳答案
我看不到谁调用了 getCompilationUnit
方法,但为了使用 ASTParser
你必须设置单元名称并设置环境(正如我所说,我不确定如果您已经这样做了),以下代码片段可能会帮助您:
// creating ASTParser
ASTParser parser = ASTParser.newParser(AST.JLS4);
// you probably want to set the kind
parser.setKind(ASTParser.K_COMPILATION_UNIT);
// you must set compilation unit name, so I just name it as a path to source file
parser.setUnitName(inputFilePath.toString());
// you must set environment params classpathEntries, sourcepathEntries, encodings, IncludeRunningVMBootclasspath
parser.setEnvironment(null, null, null, true);
// you probably want to set source
parser.setSource(fileContent);
// I can see that you actually want to do that :)
parser.setResolveBindings(true);
// creating compilation unit
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
关于java.lang.NoSuchFieldError : resources - Eclipse AST parser error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170893/