我正在尝试以编程方式更改类型的签名,确切地说,我希望让类实现接口或者将implements SomeInterface
添加到其签名中。
我得到一个类型的对象如下:
IType ejbType = jproject.findType(ejbClass);
然后我希望IType
有一个类似setSuperInterfaceNames(String[])
的方法,但只有一个方法getSuperInterfaceNames()
。
有没有可能用jdt满足我的要求?
答案 0 :(得分:1)
您可以使用Eclipse AST修改代码。粗略地说,步骤是:
1)解析源文件[CompilationUnit unit = parseAst(ejbType.getCompilationUnit())
]
public static CompilationUnit parseAst(ICompilationUnit unit, SubMonitor progress) {
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(unit);
parser.setResolveBindings(true);
return (CompilationUnit)parser.createAST(progress);
}
2)使用访客模式在CompilationUnit
中找到您要修改的类型:
unit.accept(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration node) {
IType type = (IType) node.resolveBinding().getTypeDeclaration().getJavaElement();
if (ejbType.equals(type)) {
modifyTypeDeclaration(node);
}
return false;
}
});
3)实施modifyTypeDeclaration(TypeDeclaration node)
。
我通常使用ASTRewrite
来收集编译单元(* .java文件)的所有更改,然后将它写回来,看起来像这样。
ICompilationUnit cu = ejbType.getCompilationUnit();
cu.becomeWorkingCopy(...);
CompilationUnit unit = parseAst(ejbType.getCompilationUnit())
final ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
collectChangesToUnit(unit, rewrite);
cu.applyTextEdit(rewrite.rewriteAST(), ...);
cu.commitWorkingCopy(false, ...);
如果您的案例非常简单,您还可以直接修改TypeDeclaration
。