1
藉助SO和一些文檔,我能夠快速組裝下面的代碼來生成Java源代碼。但現在我堅持嘗試添加聲明語句。我只是想創建一個看起來像下面JDT AST,如何生成聲明
Connection con = null;
try{
con = DataSource.getConnection();
}catch(Exception ex){
ex.printStackTrace();
}
我被困語句的第一個最簡單形式的聲明,'VariableDeclarationStatement」 這是我迄今爲止,但不知道怎麼用variableDeclarationFragment或variableDeclarationExpression 。
public static void main(String[] args) {
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name = ast.newQualifiedName(ast.newSimpleName("java"), ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
MethodDeclaration createMethod = createMethod("helloWorld", new HashMap<String, String>());
Block block = ast.newBlock();
//VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
//variableDeclarationFragment.
//block.statements().add(ast.newVariableDeclarationExpression((getConnectionDeclaration()));
//VariableDeclarationExpression variableDeclarationExpression = ast.newVariableDeclarationExpression(ast.newVariableDeclarationFragment());
//block.
//variableDeclarationExpression.
createMethod.setBody(block);
type.bodyDeclarations().add(createMethod);
unit.types().add(type);
System.out.println(unit);
}
這是基於過程的AST系統的缺陷。構建AST(以及難以實現的輔助功能)確實是一種痛苦(而且很脆弱:ADT的下一個版本可能會破壞您的代碼)。程序轉換引擎提供了一種替代方法:您可以使用* source *形式編寫代碼片段,幾乎完全如您在「看起來像下面的內容」中所表達的那樣。見http://en.wikipedia.org/wiki/Program_transformation –