我想用Java AST编辑几个Java类。但是我的更改不会显示在Java类文件中。Eclipse AST在更改时不改变类文件TypeDeclaration
我想要做什么?我想采取IPackageFragment
并访问所有ICompilationUnit
s。对于每个声明的类,我想将超类设置为特定的类(使用超类的限定名称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();
}
}
}
在此先感谢您的帮助!
感谢您的帮助,我现在就开始工作! – ConveniencePatterns