我最近需要修改一些 Java 代码(添加方法、更改某些字段的签名和删除方法),我认为所有这些都可以通过使用 Eclipse SDK 的 AST 来完成。
我从一些研究中知道如何在源文件中解析,但我不知道如何做上面提到的事情。有没有人知道一个好的教程,或者有人可以就如何解决这些问题给我一个简短的解释?
非常感谢,
极限编码器
编辑:
我现在开始更多地研究 JCodeModel,我认为这可能更容易使用,但我不知道是否可以将现有文档加载到其中?
如果这可行,请告诉我 ;)
再次感谢。
最佳答案
我不会在这里发布这个问题的完整源代码,因为它很长,但我会让人们开始。
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());
}
}
}
}
这应该让你们都开始了。
确实需要一些时间来适应这一点(对我而言需要很多时间)。但它确实有效,而且是我能得到的最好方法。
祝你好运;)
极限编码器
编辑:
在我忘记之前,这些是我用来使它正常工作的导入(我花了相当多的时间来组织这些):
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代表版本号。
关于java - 使用 Eclipse AST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3351451/