使用Eclipse AST

我最近需要修改一些Java代码(添加方法,更改某些字段的签名和删除方法),我认为所有这些都可以通过使用Eclipse SDK的AST来实现。

我从一些研究中知道如何解析源文件,但我不知道如何做上面提到的事情。 有没有人知道一个很好的教程,或者有人能给我一个关于如何解决这些问题的简要说明?

非常感谢,

ExtremeCoder


编辑:

我现在开始更多地了解JCodeModel,我认为这可能更容易使用,但我不知道是否可以加载现有文档?

如果这可行,请告诉我;)

再次感谢。

我不会在这里发布这个问题的完整源代码,因为它很长但我会让人们开始。

您需要的所有文档都在这里: 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 types = cu.types(); for(AbstractTypeDeclaration type : types) { if(type.getNodeType() == ASTNode.TYPE_DECLARATION) { // Class def found List 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


编辑:

在我忘记之前,这些是我用来实现这项工作的import(我花了很多时间来完成这些工作):

 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表示版本号。

您可以通过调用允许您操作AST的API来使用Eclipse。

或者您可以应用程序转换来实现您的效果,而不依赖于AST的微观细节。

作为示例,您可以编写以下程序转换:

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

将具有任意名称的整数参数添加到参数列表中。 这实现了与整组API调用相同的效果,但它更具可读性,因为它采用您的语言的表面语法(在本例中为Java)。

我们的DMS软件再造工具包可以接受这样的程序转换 ,并将它们应用于多种语言,包括Java。