鉴于我可以访问IField字段(从另一个Java文件解析),如何创建FieldDeclaration以将其添加到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));
以上
输入fieldType = ast.newSimpleType(ast.newSimpleName(typeName));
仅在typeName不是java关键字时才有效。是否有另一种方法可以简单地创建一个包含所有IField信息(修饰符,类型,变量)的fieldDeclaration
由于
答案 0 :(得分: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
答案 1 :(得分: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);