2010-07-28 106 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在内的多种语言。