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
I’ve found a way using copySubtree:
Then newType can be used to plug it into a FieldDeclaration