下面列出了org.eclipse.jdt.core.dom.SuperMethodReference#org.eclipse.jdt.core.dom.rewrite.ASTRewrite 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@inheritDoc}
*/
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);
ASTRewrite rewrite= cuRewrite.getASTRewrite();
TightSourceRangeComputer rangeComputer;
if (rewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
rangeComputer= (TightSourceRangeComputer)rewrite.getExtendedSourceRangeComputer();
} else {
rangeComputer= new TightSourceRangeComputer();
}
rangeComputer.addTightSourceNode(getForStatement());
rewrite.setTargetSourceRangeComputer(rangeComputer);
Statement statement= convert(cuRewrite, group, positionGroups);
rewrite.replace(getForStatement(), statement, group);
}
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
IBinding binding= fUnusedName.resolveBinding();
CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
TextEditGroup group= createTextEditGroup(displayString, cuRewrite);
if (binding.getKind() == IBinding.TYPE) {
ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
ASTNode declaration= root.findDeclaringNode(decl);
if (declaration.getParent() instanceof TypeDeclarationStatement) {
declaration= declaration.getParent();
}
rewrite.remove(declaration, group);
}
}
@Override
protected ASTRewrite getRewrite() {
MethodDeclaration dstMethod = findBestUpdateMatch(rpcPair);
CompilationUnit astRoot = ASTResolving.createQuickFixAST(
getCompilationUnit(), null);
createImportRewrite(astRoot);
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
MethodDeclaration rewriterDstMethod = JavaASTUtils.findMethodDeclaration(
astRoot, dstMethod.resolveBinding().getKey());
if (rewriterDstMethod == null) {
return null;
}
MethodDeclaration newSignature = computeMethodSignature(rewrite.getAST(),
rpcPair, rewriterDstMethod);
rewrite.replace(rewriterDstMethod, newSignature, null);
return rewrite;
}
private void replaceCastExpressionWithThisExpression(List<Expression> oldCastExpressions, List<Expression> newCastExpressions, TypeDeclaration subclassTypeDeclaration, AST subclassAST, ASTRewrite subclassRewriter) {
int j = 0;
for(Expression expression : oldCastExpressions) {
CastExpression castExpression = (CastExpression)expression;
if(castExpression.getType().resolveBinding().isEqualTo(subclassTypeDeclaration.resolveBinding())) {
if(castExpression.getExpression() instanceof SimpleName) {
SimpleName castSimpleName = (SimpleName)castExpression.getExpression();
if(typeVariable != null && typeVariable.getName().resolveBinding().isEqualTo(castSimpleName.resolveBinding())) {
subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
}
}
else if(castExpression.getExpression() instanceof MethodInvocation) {
MethodInvocation castMethodInvocation = (MethodInvocation)castExpression.getExpression();
if(typeMethodInvocation != null && typeMethodInvocation.subtreeMatch(new ASTMatcher(), castMethodInvocation)) {
subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
}
}
}
j++;
}
}
private Type getNewType(ASTRewrite rewrite) {
AST ast= rewrite.getAST();
Type newTypeNode= null;
ITypeBinding binding= null;
if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue();
binding= value.resolveTypeBinding();
} else if (fInvocationNode instanceof Expression) {
binding= ((Expression) fInvocationNode).resolveTypeBinding();
}
if (binding != null) {
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite());
newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext);
}
if (newTypeNode == null) {
newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
}
return newTypeNode;
}
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
AST ast= selectedNode.getAST();
SwitchStatement parent= (SwitchStatement) selectedNode.getParent();
for (Statement statement : (List<Statement>) parent.statements()) {
if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
// insert //$CASES-OMITTED$:
ASTRewrite rewrite= ASTRewrite.create(ast);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
listRewrite.insertBefore(casesOmittedComment, statement, null);
String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image);
proposals.add(proposal);
break;
}
}
}
}
/**
* Creates the method content of the moved method.
*
* @param document
* the document representing the source compilation unit
* @param declaration
* the source method declaration
* @param rewrite
* the ast rewrite to use
* @return the string representing the moved method body
* @throws BadLocationException
* if an offset into the document is invalid
*/
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
Assert.isNotNull(document);
Assert.isNotNull(declaration);
Assert.isNotNull(rewrite);
final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
final IJavaProject project= fMethod.getJavaProject();
final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
for (int index= 0; index < edits.length; index++)
marker.addChild(edits[index]);
final MultiTextEdit result= new MultiTextEdit();
result.addChild(marker);
final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
processor.getRoot().addChild(result);
processor.performEdits();
final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
private ASTRewrite doAddEnumConst(CompilationUnit astRoot) {
SimpleName node= fOriginalNode;
ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
if (newTypeDecl == null) {
astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newTypeDecl != null) {
AST ast= newTypeDecl.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
EnumConstantDeclaration constDecl= ast.newEnumConstantDeclaration();
constDecl.setName(ast.newSimpleName(node.getIdentifier()));
ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
listRewriter.insertLast(constDecl, null);
return rewrite;
}
return null;
}
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
AST ast= rewrite.getAST();
List<Expression> arguments= fArguments;
for (int i= 0; i < arguments.size(); i++) {
Expression elem= arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
// argument type
String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
Type type= evaluateParameterType(ast, elem, argTypeKey, context);
param.setType(type);
// argument name
String argNameKey= "arg_name_" + i; //$NON-NLS-1$
String name= evaluateParameterName(takenNames, elem, type, argNameKey);
param.setName(ast.newSimpleName(name));
params.add(param);
}
}
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) {
AST ast= typeDecl.getAST();
Javadoc javadoc= typeDecl.getJavadoc();
ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
List<TypeParameter> typeParams= typeDecl.typeParameters();
for (int i= typeParams.size() - 1; i >= 0; i--) {
TypeParameter decl= typeParams.get(i);
String name= '<' + decl.getName().getIdentifier() + '>';
if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) {
TagElement newTag= ast.newTagElement();
newTag.setTagName(TagElement.TAG_PARAM);
TextElement text= ast.newTextElement();
text.setText(name);
newTag.fragments().add(text);
insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$
insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl));
}
}
}
private void addEnclosingInstanceTypeParameters(final ITypeBinding[] parameters, final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) {
Assert.isNotNull(parameters);
Assert.isNotNull(declaration);
Assert.isNotNull(rewrite);
if (declaration instanceof TypeDeclaration) {
final TypeDeclaration type= (TypeDeclaration) declaration;
final List<TypeParameter> existing= type.typeParameters();
final Set<String> names= new HashSet<String>();
TypeParameter parameter= null;
for (final Iterator<TypeParameter> iterator= existing.iterator(); iterator.hasNext();) {
parameter= iterator.next();
names.add(parameter.getName().getIdentifier());
}
final ListRewrite rewriter= rewrite.getListRewrite(type, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
String name= null;
for (int index= 0; index < parameters.length; index++) {
name= parameters[index].getName();
if (!names.contains(name)) {
parameter= type.getAST().newTypeParameter();
parameter.setName(type.getAST().newSimpleName(name));
rewriter.insertLast(parameter, null);
}
}
}
}
/**
* Adds a new field to the {@link AST} using the given type and variable name. The method
* returns a {@link TextEdit} which can then be applied using the {@link #applyTextEdit(TextEdit)} method.
*
* @param type
* @param varName
* @return a {@link TextEdit} which represents the changes which would be made, or <code>null</code> if the field
* can not be created.
*/
public TextEdit addField(String type, String varName, boolean publicField, boolean staticField, boolean finalField, String value) {
if (isReadOnly())
return null;
if (!domInitialized)
initDomAST();
boolean isStatic = isBodyStatic();
int modifiers = (!publicField) ? Modifier.PRIVATE : Modifier.PUBLIC;
if (isStatic || staticField) {
modifiers |= Modifier.STATIC;
}
if (finalField) {
modifiers |= Modifier.FINAL;
}
ASTRewrite rewrite= ASTRewrite.create(parentDeclaration.getAST());
VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, parentDeclaration, modifiers, varName, type, value);
TextEdit te = rewrite.rewriteAST(getDocument(), null);
return te;
}
@Override
protected ASTRewrite getRewrite() throws CoreException {
AST ast= fTypeNode.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
createImportRewrite((CompilationUnit) fTypeNode.getRoot());
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject());
if (!settings.createComments) {
settings= null;
}
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite());
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings);
rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null);
addLinkedRanges(rewrite, newMethodDecl);
return rewrite;
}
@Override
protected ASTRewrite getRewrite() throws CoreException {
ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding);
ASTNode declNode= null;
CompilationUnit newRoot= fAstRoot;
if (boundNode != null) {
declNode= boundNode; // is same CU
} else {
newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
declNode= newRoot.findDeclaringNode(fBinding.getKey());
}
ImportRewrite imports= createImportRewrite(newRoot);
if (declNode instanceof TypeDeclaration) {
AST ast= declNode.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports);
Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER);
ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
listRewrite.insertLast(newInterface, null);
return rewrite;
}
return null;
}
protected Expression createEqualsExpression(ASTRewrite rewrite, InfixExpression stringEqualityCheck) {
Assert.isNotNull(rewrite);
Assert.isNotNull(stringEqualityCheck);
final AST ast = rewrite.getAST();
MethodInvocation equalsInvocation = ast.newMethodInvocation();
Expression leftOperand = createLeftOperand(rewrite, stringEqualityCheck.getLeftOperand());
Expression rightOperand = createRightOperand(rewrite, stringEqualityCheck.getRightOperand());
equalsInvocation.setName(ast.newSimpleName(EQUALS_METHOD_NAME));
equalsInvocation.setExpression(leftOperand);
ListRewrite argumentsRewrite = rewrite.getListRewrite(equalsInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
argumentsRewrite.insertLast(rightOperand, null);
return equalsInvocation;
}
protected TryStatement copyTryStatement(ASTRewrite sourceRewriter, AST ast, TryStatement tryStatementParent) {
TryStatement newTryStatement = ast.newTryStatement();
ListRewrite resourceRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.RESOURCES_PROPERTY);
List<VariableDeclarationExpression> resources = tryStatementParent.resources();
for(VariableDeclarationExpression expression : resources) {
resourceRewrite.insertLast(expression, null);
}
ListRewrite catchClauseRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.CATCH_CLAUSES_PROPERTY);
List<CatchClause> catchClauses = tryStatementParent.catchClauses();
for(CatchClause catchClause : catchClauses) {
catchClauseRewrite.insertLast(catchClause, null);
}
if(tryStatementParent.getFinally() != null) {
sourceRewriter.set(newTryStatement, TryStatement.FINALLY_PROPERTY, tryStatementParent.getFinally(), null);
}
return newTryStatement;
}
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
AST ast = selectedNode.getAST();
SwitchStatement parent = (SwitchStatement) selectedNode.getParent();
for (Statement statement : (List<Statement>) parent.statements()) {
if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
// insert //$CASES-OMITTED$:
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
listRewrite.insertBefore(casesOmittedComment, statement, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
proposals.add(proposal);
break;
}
}
}
}
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
if (tryStatement == null || tryStatement.getFinally() != null) {
return false;
}
Statement statement= ASTResolving.findParentStatement(node);
if (tryStatement != statement && tryStatement.getBody() != statement) {
return false; // an node inside a catch or finally block
}
if (resultingCollections == null) {
return true;
}
AST ast= tryStatement.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
Block finallyBody= ast.newBlock();
rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);
String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image);
resultingCollections.add(proposal);
return true;
}
@Override
protected ASTRewrite getRewrite() throws CoreException {
AST ast= fTypeNode.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
createImportRewrite((CompilationUnit) fTypeNode.getRoot());
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject());
if (!settings.createComments) {
settings= null;
}
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite());
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings);
rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null);
addLinkedRanges(rewrite, newMethodDecl);
return rewrite;
}
private Javadoc createJavadocForStub(final String enclosingTypeName, final MethodDeclaration oldMethod, final MethodDeclaration newMethodNode, final ICompilationUnit cu, final ASTRewrite rewrite) throws CoreException {
if (fSettings.createComments) {
final IMethodBinding binding= oldMethod.resolveBinding();
if (binding != null) {
final ITypeBinding[] params= binding.getParameterTypes();
final String fullTypeName= getDestinationType().getFullyQualifiedName('.');
final String[] fullParamNames= new String[params.length];
for (int i= 0; i < fullParamNames.length; i++) {
fullParamNames[i]= Bindings.getFullyQualifiedName(params[i]);
}
final String comment= CodeGeneration.getMethodComment(cu, enclosingTypeName, newMethodNode, false, binding.getName(), fullTypeName, fullParamNames, StubUtility.getLineDelimiterUsed(cu));
if (comment != null)
return (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
}
}
return null;
}
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) {
AST ast= typeDecl.getAST();
Javadoc javadoc= typeDecl.getJavadoc();
ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
List<TypeParameter> typeParams= typeDecl.typeParameters();
for (int i= typeParams.size() - 1; i >= 0; i--) {
TypeParameter decl= typeParams.get(i);
String name= '<' + decl.getName().getIdentifier() + '>';
if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) {
TagElement newTag= ast.newTagElement();
newTag.setTagName(TagElement.TAG_PARAM);
TextElement text= ast.newTextElement();
text.setText(name);
newTag.fragments().add(text);
insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$
insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl));
}
}
}
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);
IJavaElement[] importDeclarations= container.getChildren();
for (int i= 0; i < importDeclarations.length; i++) {
IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];
ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);
if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
listRewrite.insertFirst(copiedNode, null);
} else {
listRewrite.insertLast(copiedNode, null);
}
}
}
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) {
AST ast = newMethodDeclaration.getAST();
SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
Type fieldType = null;
FieldDeclaration[] fields = sourceTypeDeclaration.getFields();
for(FieldDeclaration field : fields) {
List<VariableDeclarationFragment> fragments = field.fragments();
for(VariableDeclarationFragment fragment : fragments) {
if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) {
fieldType = field.getType();
break;
}
}
}
targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null);
ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
parametersRewrite.insertLast(parameter, null);
this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier());
this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding());
addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier());
}
private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
Name privilegedActionName;
if (isUpdateImports()) {
privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName());
} else {
privilegedActionName = ast.newName(PrivilegedAction.class.getName());
}
SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName);
ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType);
Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
List<Type> typeArguments = checkedList(privilegedActionType.typeArguments());
typeArguments.add(typeArgument);
return privilegedActionType;
}
public void addJsonDeserializeAnnotation(CompilationUnitModificationDomain compilationUnitModificationDomain, TypeDeclaration builderType) {
AST ast = compilationUnitModificationDomain.getAst();
ASTRewrite rewriter = compilationUnitModificationDomain.getAstRewriter();
ListRewrite modifierRewrite = rewriter.getListRewrite(compilationUnitModificationDomain.getOriginalType(), TypeDeclaration.MODIFIERS2_PROPERTY);
NormalAnnotation annotation = createAnnotation(ast, compilationUnitModificationDomain, builderType);
modifierRewrite.insertFirst(annotation, null);
importRepository.addImport(StaticPreferences.JSON_DESERIALIZE_FULLY_QUALIFIED_NAME);
}
/**
* Creates an {@link Assignment} as first expression appearing in an index based
* <code>for</code> loop's body. This Assignment declares a local variable and initializes it
* using the {@link List}'s current element identified by the loop index.
*
* @param rewrite the current {@link ASTRewrite} instance
* @param loopVariableName the name of the index variable in String representation
* @return a completed {@link Assignment} containing the mentioned declaration and
* initialization
*/
private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
AST ast= rewrite.getAST();
ITypeBinding loopOverType= extractElementType(ast);
Assignment assignResolvedVariable= ast.newAssignment();
// left hand side
SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment();
resolvedVariableDeclarationFragment.setName(resolvedVariableName);
VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);
// right hand side
MethodInvocation invokeGetExpression= ast.newMethodInvocation();
invokeGetExpression.setName(ast.newSimpleName("get")); //$NON-NLS-1$
SimpleName indexVariableName= ast.newSimpleName(loopVariableName.getIdentifier());
addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
invokeGetExpression.arguments().add(indexVariableName);
invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
assignResolvedVariable.setRightHandSide(invokeGetExpression);
assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);
return assignResolvedVariable;
}
public ProposalParameter(boolean useSuper, ICompilationUnit compilationUnit, ASTRewrite rewrite, Expression accessNode, Expression qualifier, IVariableBinding variableBinding) {
this.useSuper = useSuper;
this.compilationUnit = compilationUnit;
this.astRewrite = rewrite;
this.accessNode = accessNode;
this.qualifier = qualifier;
this.variableBinding = variableBinding;
}
private static Modifier removeModifier(final MethodDeclaration decl, final ASTRewrite rewrite, final int modifier) {
Modifier modifierNode= ASTNodes.findModifierNode(modifier, decl.modifiers());
if (modifierNode != null) {
rewrite.remove(modifierNode, null);
}
return modifierNode;
}
/**
* Resolves name proposals by the given basename and adds a {@link LinkedPosition} to the
* returned {@link SimpleName} expression.
*
* @param rewrite the current instance of an {@link ASTRewrite}
* @param basename the base string to use for proposal calculation
* @param excludedName a name that cannot be used for the variable; <code>null</code> if none
* @param firstLinkedProposal true if the generated name is the first {@link LinkedPosition} to
* edit in the current {@link CompilationUnit}, false otherwise
* @return the linked {@link SimpleName} instance based on the name proposals
*/
private SimpleName resolveLinkedVariableNameWithProposals(ASTRewrite rewrite, String basename, String excludedName, boolean firstLinkedProposal) {
AST ast= rewrite.getAST();
String[] nameProposals= getVariableNameProposals(basename, excludedName);
SimpleName forDeclarationName= ast.newSimpleName(nameProposals.length > 0 ? nameProposals[0] : basename);
for (int i= 0; i < nameProposals.length; i++) {
addLinkedPositionProposal(forDeclarationName.getIdentifier(), nameProposals[i], null);
}
// mark declaration name as editable
addLinkedPosition(rewrite.track(forDeclarationName), firstLinkedProposal, forDeclarationName.getIdentifier());
return forDeclarationName;
}
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, org.eclipse.jdt.core.dom.ASTNode newTypeDecl, int modifiers, String varName, String qualifiedName, String value) {
ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl);
AST ast = newTypeDecl.getAST();
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
newDeclFrag.setName(ast.newSimpleName(varName));
Type type = createType(Signature.createTypeSignature(qualifiedName, true), ast);
if (value != null && value.trim().length() > 0) {
Expression e = createExpression(value);
Expression ne = (Expression) org.eclipse.jdt.core.dom.ASTNode.copySubtree(ast, e);
newDeclFrag.setInitializer(ne);
} else {
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
}
}
FieldDeclaration newDecl = ast.newFieldDeclaration(newDeclFrag);
newDecl.setType(type);
newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
int insertIndex = findFieldInsertIndex(decls, getCompletionOffset(), modifiers);
rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);
return newDeclFrag;
}