[英]Modify existing Java source programatically with Eclipse JDT ASTRewrite as a standalone application
[英]How to add a method source to an existing java file with JDT?
我正在编写一个简单的 eclipse 插件,它是一个代码生成器。 用户可以选择现有的方法,然后在相应的测试文件中生成一个新的测试方法,使用 JDT。
假设测试文件已经存在,其内容为:
public class UserTest extends TestCase {
public void setUp(){}
public void tearDown(){}
public void testCtor(){}
}
现在我已经生成了一些测试代码:
/** complex javadoc */
public void testSetName() {
....
// complex logic
}
我想要做的是将 append 到现有的UserTest
。 我必须编码:
String sourceContent = FileUtils.readFileToString("UserTest.java", "UTF-8");
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(content.toCharArray());
CompilationUnit testUnit = (CompilationUnit) parser.createAST(null);
String newTestCode = "public void testSetName() { .... }";
// get the first type
final List<TypeDeclaration> list = new ArrayList<TypeDeclaration>();
testUnit .accept(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration node) {
list.add(node);
return false;
}
});
TypeDeclaration type = list.get(0);
type.insertMethod(newTestCode); // ! no this method: insertMethod
但是没有这样的方法insertMethod
。
我现在知道两种选择:
jdt
,只是将新代码插入到测试文件中,在 last 之前}
testUnit.getAST().newMethodDeclaration()
创建一个方法,然后更新它。 但是我不喜欢这两个选项,我希望有类似insertMethod
的东西,它可以让我 append 一些文本到测试编译单元,或者将测试代码转换为 MethodDeclaration,然后 append 到测试编译单元。
更新
我看到了nonty的回答,发现jdt中有两个CompilationUnit
。 一个是org.eclipse.jdt.internal.core.CompilationUnit
,另一个是org.eclipse.jdt.core.dom.CompilationUnit
。 我用的是第二个,nonty用的是第一个。
我需要补充一下我的问题:一开始我想创建一个eclipse-plugin,但后来发现很难通过swt创建一个复杂的UI,所以我决定创建一个web应用程序来生成代码。 我从 eclipse 复制了那些 jdt jars,所以我可以只使用org.eclipse.jdt.core.dom.CompilationUnit
。
有没有办法在org.eclipse.jdt.internal.core.CompilationUnit
之外使用 org.eclipse.jdt.internal.core.CompilationUnit?
JavaCore 有一个从给定的 IFile 创建 CompilationUnit 的方法。
IFile file;
JavaCore.createCompilationUnitFrom(file);
出什么问题了
...
String newTestCode = "public void testSetName() { .... }";
IProgressMonitor monitor = new NullProgressMonitor();
IMethod method = testUnit.getTypes[0].createMethod(newTestCode, null, false, monitor);
您甚至可以指定在何处添加新方法以及是否“覆盖”任何现有方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.