【发布时间】:2017-07-05 20:49:52
【问题描述】:
我正在尝试使用 Java AST 编辑几个 Java 类。但是我的更改不会显示在 Java 类文件中。
我具体想做什么?我想带一个IPackageFragment 并访问所有ICompilationUnits。对于每个声明的类,我想将超类设置为特定类(使用超类的限定名称because it is an Xtend class)。我还尝试通过 Document 类应用编辑。
例如:一个类main.model.someClass应该继承自wrappers.main.model.someClassWrapper
我对 JDT API 比较陌生,所以我找不到类文件没有更改的原因。我已经检查了this post,但它对我没有帮助。我试图尽可能接近How To Train the JDT Dragon 中的示例,我从 Stackoverflow 获得的其他提示/示例。但它不会起作用。
我就是这样做的:
private void editTypesIn(IPackageFragment myPackage) throws JavaModelException {
for (ICompilationUnit unit : myPackage.getCompilationUnits()) {
TypeVisitor visitor = new TypeVisitor(myPackage.getElementName(), unit);
unit.becomeWorkingCopy(new NullProgressMonitor());
CompilationUnit parse = parse(unit);
parse.recordModifications();
parse.accept(visitor);
}
}
private static CompilationUnit parse(ICompilationUnit unit) {
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
return (CompilationUnit) parser.createAST(null); // parse
}
这是访问者类:
public class TypeVisitor extends ASTVisitor {
private final String currentPackage;
private final ICompilationUnit compilationUnit;
public TypeVisitor(String currentPackage, ICompilationUnit compilationUnit) {
this.currentPackage = currentPackage;
this.compilationUnit = compilationUnit;
}
@Override
public boolean visit(TypeDeclaration node) {
if (!node.isInterface()) { // is class
setSuperClass(node, "wrappers." + currentPackage + "." + node.getName().toString() + "Wrapper");
}
return super.visit(node);
}
public void setSuperClass(TypeDeclaration declaration, String qualifiedName) {
try {
// create ast and rewrite:
AST ast = declaration.getAST();
ASTRewrite astRewrite = ASTRewrite.create(ast);
// set super:
Name name = ast.newName(qualifiedName);
Type type = ast.newSimpleType(name);
declaration.setSuperclassType(type);
// apply changes
TextEdit edits = astRewrite.rewriteAST();
compilationUnit.applyTextEdit(edits, new NullProgressMonitor());
compilationUnit.commitWorkingCopy(true, new NullProgressMonitor());
} catch (JavaModelException exception) {
exception.printStackTrace();
} catch (IllegalArgumentException exception) {
exception.printStackTrace();
} catch (MalformedTreeException exception) {
exception.printStackTrace();
}
}
}
提前感谢您的帮助!
【问题讨论】:
标签: java eclipse eclipse-plugin eclipse-jdt eclipse-pde