javacoder
javacoder

Reputation: 752

How do I create a FieldDeclaration given an IField (Eclipe plugin)

Given that I have access to an IField field (parsed from another Java file), how do I create a FieldDeclaration in order to add it to a AST?

    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));

The above

Type fieldType = ast.newSimpleType(ast.newSimpleName(typeName));

only works only if typeName is not a java keyword. Is there another way to simply create a fieldDeclaration with all the IField info (modifier, type, variable)

Thanks

Upvotes: 1

Views: 1021

Answers (2)

oshai
oshai

Reputation: 15365

you can do something like this:

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));

and if you want to init it:

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);

Upvotes: 0

javacoder
javacoder

Reputation: 752

I've found a way using copySubtree:

    AST ast = targetCompilationUnit.getAST();

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

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

Then newType can be used to plug it into a FieldDeclaration

Upvotes: 1

Related Questions