簡體   English   中英

如何使用 JDT 將方法源添加到現有 java 文件?

[英]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

我現在知道兩種選擇:

  1. 不要使用jdt ,只是將新代碼插入到測試文件中,在 last 之前}
  2. 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM