Theo điều này old article, bạn sẽ có thể gọi trình phân tích cú pháp AST độc lập với ngữ cảnh ứng dụng của bạn (plugin eclipse hay không).
ASTParser parser = ASTParser.newParser(AST.JLS2);
parser.setSource("".toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
unit.recordModifications();
AST ast = unit.getAST();
alt text http://www.ibm.com/developerworks/opensource/library/os-ast/astexplorer.gif
Từ này bug entry:
ASTParser trong 3.0 có thể được sử dụng trong một chương trình độc lập để tạo Eclipse ASTs mà không thực sự chạy Eclipse. Như các tài liệu nói:
char[] source = ...;
ASTParser parser = ASTParser.newParser(AST.JLS2); // handles JLS2 (J2SE 1.4)
parser.setSource(source);
CompilationUnit result = (CompilationUnit) parser.createAST(null);
Do đó this thread nỗ lực để phân tích một nguồn java rất ngắn:
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;
public class Test{
public static void main(String[] args){
Test t= new Test();
t.runtest();
}
void runtest(){
Document doc = new Document("import java.util.List;\nclass X {}\n");
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
parser.setSource(doc.get().toCharArray());
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.recordModifications();
AST ast = cu.getAST();
ImportDeclaration id = ast.newImportDeclaration();
id.setName(ast.newName(new String[] {"java", "util", "Set"}));
cu.imports().add(id); // add import declaration at end
TextEdit edits = cu.rewrite(doc, null);
}
}
bạn đá - Tôi đã nhân đôi này và đặt nó trên github ở đây: https: //github.com/juliangamble/ASTTest – hawkeye
@hawkeye: tuyệt vời. +1 cho giải pháp cập nhật hơn nhiều. – VonC
làm thế nào tôi có thể nhận được các lọ cần thiết khác ngoài commons-io? –