2010-11-15 112 views
1

鑑於我可以訪問IField字段(從另一個Java文件解析),我如何創建FieldDeclaration以將其添加到AST?如何給IField創建FieldDeclaration(Eclipe插件)

String varName = field.getElementName(); 
    String typeName = Signature.toString(field.getTypeSignature()); 

    VariableDeclarationFragment fieldFrag = ast.newVariableDeclarationFragment(); 
    fieldFrag.setName(ast.newSimpleName(varName)); 
    FieldDeclaration field = ast.newFieldDeclaration(fieldFrag); 
    Type fieldType = ast.newSimpleType(ast.newSimpleName(typeName)); 
    field.setType(fieldType); 
    field.modifiers().add(ast.newModifier(modifierKeyword)); 

上面

類型的字段類型= ast.newSimpleType(ast.newSimpleName(typeName的));

僅當typeName不是java關鍵字時纔有效。有另一種方式來簡單地創建了所有IField信息一fieldDeclaration(改性劑,類型,變量)

感謝

回答

1

我發現使用copySubtree方式:

AST ast = targetCompilationUnit.getAST(); 

    FieldDeclaration oldFieldDeclaration = ASTNodeSearchUtil.getFieldDeclarationNode(field, sourceCompilationUnit); 
    Type oldType = oldFieldDeclaration.getType(); 

    Type newType = (Type) ASTNode.copySubtree(ast, oldType); 

然後NEWTYPE可用於將其插入FieldDeclaration

0

你可以做這樣的事情:

VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); 
fragment.setName(ast.newSimpleName("log")); 
final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); 
declaration.setType(ast.newSimpleType(ast.newName("Logger"))); 
declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); 

如果你想初始化它:

MethodInvocation methodInvocation = ast.newMethodInvocation(); 
methodInvocation.setName(ast.newSimpleName("getLogger")); 
methodInvocation.setExpression(ast.newSimpleName("Logger")); 
TypeLiteral typeLiteral = ast.newTypeLiteral(); 
typeLiteral.setType(ast.newSimpleType(ast.newName(className))); 
methodInvocation.arguments().add(typeLiteral); 
fragment.setInitializer(methodInvocation); 
+0

我不認爲這將工作時,SimpleType是一個原語 – javacoder 2010-11-29 23:17:40