2010-07-28 45 views
6

我最近需要修改一些Java代碼(添加方法,更改某些字段的簽名和刪除方法),我認爲所有這些都可以通過使用Eclipse SDK的AST。使用Eclipse AST

我從一些研究中知道如何解析源文件,但我不知道如何去做上面提到的事情。有沒有人知道一個很好的教程,或有人可以給我一個關於如何解決這些問題的簡要說明?

非常感謝,

ExtremeCoder


編輯:

我現在已經開始尋找更多的進入JCodeModel,我認爲這可能是更容易使用,但我不知道現有的文檔是否可以加載到它?

如果這可以工作讓我知道;)

再次感謝。

回答

4

我不會在這裏發佈整個源代碼到這個問題,因爲它很長,但我會讓人們開始。

所有你需要的文檔是在這裏:http://publib.boulder.ibm.com/infocenter/iadthelp/v6r0/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/package-summary.html

Document document = new Document("import java.util.List;\n\nclass X\n{\n\n\tpublic void deleteme()\n\t{\n\t}\n\n}\n"); 
ASTParser parser = ASTParser.newParser(AST.JLS3); 
parser.setSource(document.get().toCharArray()); 
CompilationUnit cu = (CompilationUnit)parser.createAST(null); 
cu.recordModifications(); 

將從您在將源代碼爲您創建一個編譯單元

現在,這是一個簡單的函數,打印出你所傳遞的類定義中的所有方法:

List<AbstractTypeDeclaration> types = cu.types(); 
for(AbstractTypeDeclaration type : types) { 
    if(type.getNodeType() == ASTNode.TYPE_DECLARATION) { 
     // Class def found 
     List<BodyDeclaration> bodies = type.bodyDeclarations(); 
     for(BodyDeclaration body : bodies) { 
      if(body.getNodeType() == ASTNode.METHOD_DECLARATION) { 
       MethodDeclaration method = (MethodDeclaration)body; 
       System.out.println("method declaration: "); 
       System.out.println("name: " + method.getName().getFullyQualifiedName()); 
       System.out.println("modifiers: " + method.getModifiers()); 
       System.out.println("return type: " + method.getReturnType2().toString()); 
      } 
     } 
    } 
} 

這應該讓你們都開始了。

它需要一些時間來適應這個(對我來說很多)。但它確實有效,而且是我可以得到的最好方法。

祝你好運;)

ExtremeCoder


編輯:

我忘記之前,這些是我以前得到這個工作的進口(我花了相當多的時間得到這些組織):

org.eclipse.jdt.core_xxxx.jar 
org.eclipse.core.resources_xxxx.jar 
org.eclipse.core.jobs_xxxx.jar 
org.eclipse.core.runtime_xxxx.jar 
org.eclipse.core.contenttype_xxxx.jar 
org.eclipse.equinox.common_xxxx.jar 
org.eclipse.equinox.preferences_xxxx.jar 
org.eclipse.osgi_xxxx.jar 
org.eclipse.text_xxxx.jar 

其中,xxxx表示版本號。

1

您可以通過調用允許您操縱AST的API來完成此操作。

或者您可以應用程序轉換來實現您的效果,而不依賴於AST的微觀細節。

正如你可能會寫下面的程序轉型的例子:

add_int_parameter(p:parameter_list, i: identifier): parameters -> parameters 
    " \p " -> " \p , int \i"; 

以任意名字命名的參數列表中添加的整數參數。這實現了與整個API調用相同的效果,但它更易於閱讀,因爲它使用的是語言的表面語法(在本例中爲Java)。

我們的DMS Software Reengineering Toolkit可以接受這樣的program transformations並將它們應用於包括Java在內的多種語言。