下面列出了org.eclipse.jdt.core.dom.MethodDeclaration#setReturnType2 ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private MethodDeclaration createNewWithMethod(AST ast, String fieldName, Block newBlock,
SingleVariableDeclaration methodParameterDeclaration, TypeDeclaration builderType,
BuilderField builderField) {
MethodDeclaration builderMethod = ast.newMethodDeclaration();
builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
builderMethod.setReturnType2(ast.newSimpleType(
ast.newName(builderType.getName().getIdentifier())));
builderMethod.setBody(newBlock);
builderMethod.parameters().add(methodParameterDeclaration);
javadocAdder.addJavadocForWithMethod(ast, fieldName, builderMethod);
if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
markerAnnotationAttacher.attachNonNull(ast, builderMethod);
}
builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
return builderMethod;
}
private MethodDeclaration createGetOuterHelper() {
String outerTypeName= fType.getDeclaringClass().getTypeDeclaration().getName();
MethodDeclaration helperMethod= fAst.newMethodDeclaration();
helperMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PRIVATE));
helperMethod.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
helperMethod.setConstructor(false);
helperMethod.setReturnType2(fAst.newSimpleType(fAst.newSimpleName(outerTypeName)));
Block body= fAst.newBlock();
helperMethod.setBody(body);
ThisExpression thisExpression= fAst.newThisExpression();
thisExpression.setQualifier(fAst.newSimpleName(outerTypeName));
ReturnStatement endReturn= fAst.newReturnStatement();
endReturn.setExpression(thisExpression);
body.statements().add(endReturn);
return helperMethod;
}
private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
SimpleName methodName = ast.newSimpleName("run");
Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());
modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
methodDeclaration.setName(methodName);
methodDeclaration.setReturnType2(returnType);
methodDeclaration.setBody(methodBody);
return methodDeclaration;
}
@Override
protected MethodDeclaration createMethodDeclaration(AST ast) {
MethodDeclaration asyncMethodDecl = ast.newMethodDeclaration();
// New method has same name as original
String methodName = getSyncMethodDeclaration().getName().getIdentifier();
asyncMethodDecl.setName(ast.newSimpleName(methodName));
// Async method has void return type by default (the user can also use
// Request or RequestBuilder as the return type to get more functionality).
// TODO: investigate whether we can enter linked mode after the fix is
// applied, so the user can choose what return type to use. See
// LinkedCorrectionProposal, which is a subclass of
// ASTRewriteCorrectionProposal.
asyncMethodDecl.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
addAsyncParameters(ast, asyncMethodDecl);
// TODO: generate comments for new method
return asyncMethodDecl;
}
/**
* Generates a sync/async method declaration based on the associated
* async/sync method signature.
*/
private MethodDeclaration computeMethodSignature(AST ast, RpcPair rpcPair,
MethodDeclaration dstMethod) {
MethodDeclaration method = ast.newMethodDeclaration();
// New method has same name as original
String methodName = rpcPair.srcMethod.getName().getIdentifier();
method.setName(ast.newSimpleName(methodName));
// Update the parameters
@SuppressWarnings("unchecked")
List<SingleVariableDeclaration> params = method.parameters();
params.addAll(computeParams(ast, rpcPair.srcMethod, dstMethod,
getImportRewrite()));
// Update the return type
method.setReturnType2(computeReturnType(ast, rpcPair.srcMethod, dstMethod,
getImportRewrite()));
return method;
}
@Override
protected MethodDeclaration createMethodDeclaration(AST ast) {
MethodDeclaration syncMethodDecl = ast.newMethodDeclaration();
// New method has same name as original
String methodName = getAsyncMethodDeclaration().getName().getIdentifier();
syncMethodDecl.setName(ast.newSimpleName(methodName));
syncMethodDecl.setReturnType2(Util.computeSyncReturnType(ast,
getAsyncMethodDeclaration(), getImportRewrite()));
addSyncParameters(ast, syncMethodDecl);
// TODO: generate comments for new method
return syncMethodDecl;
}
private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, CompilationUnitRewrite cuRewrite) {
AST ast= subclass.getAST();
MethodDeclaration newConstructor= ast.newMethodDeclaration();
newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier()));
newConstructor.setConstructor(true);
newConstructor.setJavadoc(null);
newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass)));
newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
Block body= ast.newBlock();
newConstructor.setBody(body);
SuperConstructorInvocation superCall= ast.newSuperConstructorInvocation();
addArgumentsToNewSuperConstructorCall(superCall, cuRewrite);
body.statements().add(superCall);
String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_add_constructor;
TextEditGroup description= cuRewrite.createGroupDescription(msg);
cuRewrite.getASTRewrite().getListRewrite(subclass, subclass.getBodyDeclarationsProperty()).insertFirst(newConstructor, description);
// TODO use AbstractTypeDeclaration
}
public MethodDeclaration createMethod(AST ast, TypeDeclaration originalType) {
MethodDeclaration method = ast.newMethodDeclaration();
method.setName(ast.newSimpleName(getBuildMethodName(originalType)));
method.setReturnType2(ast.newSimpleType(ast.newName(originalType.getName().toString())));
if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
markerAnnotationAttacher.attachNonNull(ast, method);
}
method.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
return method;
}
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
Type type = field.getType();
MethodDeclaration result = ast.newMethodDeclaration();
result.setName(ast.newSimpleName(fGetterName));
result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
result.setReturnType2(returnType);
Block block = ast.newBlock();
result.setBody(block);
String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
if (body != null) {
body = body.substring(0, body.lastIndexOf(lineDelimiter));
ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
block.statements().add(getterNode);
} else {
ReturnStatement rs = ast.newReturnStatement();
rs.setExpression(ast.newSimpleName(fField.getElementName()));
block.statements().add(rs);
}
if (fGenerateJavadoc) {
String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
if (string != null) {
Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
result.setJavadoc(javadoc);
}
}
return result;
}
protected void copyReturnType(final ASTRewrite rewrite, final ICompilationUnit unit, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping) throws JavaModelException {
Type newReturnType= null;
if (mapping.length > 0)
newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, mapping, rewrite);
else
newReturnType= createPlaceholderForType(oldMethod.getReturnType2(), unit, rewrite);
newMethod.setReturnType2(newReturnType);
}
private MethodDeclaration createGetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
AST ast= cuRewrite.getAST();
ICompilationUnit cu= cuRewrite.getCu();
IJavaProject project= cu.getJavaProject();
MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
String fieldName= pi.getNewName();
String getterName= getGetterName(pi, ast, project);
String lineDelim= StubUtility.getLineDelimiterUsed(cu);
String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
if (createComments(project)) {
String comment= CodeGeneration.getGetterComment(cu, declaringType, getterName, fieldName, pi.getNewTypeName(), bareFieldname, lineDelim);
if (comment != null)
methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
}
methodDeclaration.setName(ast.newSimpleName(getterName));
methodDeclaration.setReturnType2(importBinding(pi.getNewTypeBinding(), cuRewrite));
methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
Block block= ast.newBlock();
methodDeclaration.setBody(block);
boolean useThis= StubUtility.useThisForFieldAccess(project);
if (useThis) {
fieldName= "this." + fieldName; //$NON-NLS-1$
}
String bodyContent= CodeGeneration.getGetterMethodBodyContent(cu, declaringType, getterName, fieldName, lineDelim);
ASTNode getterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
block.statements().add(getterBody);
return methodDeclaration;
}
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
Type type= field.getType();
MethodDeclaration result= ast.newMethodDeclaration();
result.setName(ast.newSimpleName(fGetterName));
result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
Type returnType= DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
result.setReturnType2(returnType);
Block block= ast.newBlock();
result.setBody(block);
String body= CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
if (body != null) {
ASTNode getterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
block.statements().add(getterNode);
} else {
ReturnStatement rs= ast.newReturnStatement();
rs.setExpression(ast.newSimpleName(fField.getElementName()));
block.statements().add(rs);
}
if (fGenerateJavadoc) {
String string= CodeGeneration.getGetterComment(
fField.getCompilationUnit() , getTypeName(field.getParent()), fGetterName,
fField.getElementName(), ASTNodes.asString(type),
StubUtility.getBaseName(fField),
lineDelimiter);
if (string != null) {
Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
result.setJavadoc(javadoc);
}
}
return result;
}
public boolean visit(MethodDeclaration node){
if(node.getName().getFullyQualifiedName().equals(_methodName)){
ASTNode parent = node.getParent();
while(parent != null){
if(parent instanceof TypeDeclaration){
break;
}
parent = parent.getParent();
}
if(parent == null){
return false;
}
TypeDeclaration typeDeclaration = (TypeDeclaration) parent;
Set<Integer> assertLines = analysis(node);
if(assertLines.size() <= 1){
_purifiedTestCases.add(_clazz + "::" + _methodName);
} else {
int methodID = 1;
for(Integer line : assertLines){
AST ast = AST.newAST(AST.JLS8);
MethodDeclaration newMethod = ast.newMethodDeclaration();
String newName = _methodName + "_purify_" + methodID;
methodID ++;
newMethod.setName(ast.newSimpleName(newName));
newMethod.modifiers().addAll(ASTNode.copySubtrees(ast, node.modifiers()));
if(node.thrownExceptionTypes().size() > 0){
newMethod.thrownExceptionTypes().addAll(ASTNode.copySubtrees(ast, node.thrownExceptionTypes()));
}
newMethod.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
List<ASTNode> result = new ArrayList<>();
for(int i = 0; i < line; i++){
if(assertLines.contains(i)){
continue;
}
result.add((ASTNode) node.getBody().statements().get(i));
}
result.add((ASTNode) node.getBody().statements().get(line));
// cannot simply remove duplicate assignment since it may cause side-effect
// result = simplify(result);
Block body = ast.newBlock();
for(ASTNode astNode : result){
body.statements().add(ASTNode.copySubtree(ast, astNode));
}
newMethod.setBody(body);
typeDeclaration.bodyDeclarations().add(ASTNode.copySubtree(node.getAST(), newMethod));
_purifiedTestCases.add(_clazz + "::" + newName);
}
node.getBody().statements().clear();
}
return false;
}
return true;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
SimpleName newNameNode= getNewName(rewrite);
decl.setConstructor(isConstructor());
addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());
ArrayList<String> takenNames= new ArrayList<String>();
addNewTypeParameters(rewrite, takenNames, decl.typeParameters());
decl.setName(newNameNode);
IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
takenNames.add(declaredFields[i].getName());
}
String bodyStatement= ""; //$NON-NLS-1$
if (!isConstructor()) {
Type returnType= getNewMethodType(rewrite);
decl.setReturnType2(returnType);
boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
if (!fSenderBinding.isInterface() && !isVoid) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
}
}
addNewParameters(rewrite, takenNames, decl.parameters());
addNewExceptions(rewrite, decl.thrownExceptionTypes());
Block body= null;
if (!fSenderBinding.isInterface()) {
body= ast.newBlock();
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), newNameNode.getIdentifier(), isConstructor(), bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ReturnStatement todoNode= (ReturnStatement)rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject());
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
Type type = field.getType();
MethodDeclaration result = ast.newMethodDeclaration();
result.setName(ast.newSimpleName(fSetterName));
result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
if (fSetterMustReturnValue) {
result.setReturnType2((Type) rewriter.createCopyTarget(type));
}
SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
result.parameters().add(param);
param.setName(ast.newSimpleName(fArgName));
param.setType((Type) rewriter.createCopyTarget(type));
List<Dimension> extraDimensions = DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter);
param.extraDimensions().addAll(extraDimensions);
Block block = ast.newBlock();
result.setBody(block);
String fieldAccess = createFieldAccess();
String body = CodeGeneration.getSetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fieldAccess, fArgName, lineDelimiter);
if (body != null) {
body = body.substring(0, body.lastIndexOf(lineDelimiter));
ASTNode setterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
block.statements().add(setterNode);
} else {
Assignment ass = ast.newAssignment();
ass.setLeftHandSide((Expression) rewriter.createStringPlaceholder(fieldAccess, ASTNode.QUALIFIED_NAME));
ass.setRightHandSide(ast.newSimpleName(fArgName));
block.statements().add(ass);
}
if (fSetterMustReturnValue) {
ReturnStatement rs = ast.newReturnStatement();
rs.setExpression(ast.newSimpleName(fArgName));
block.statements().add(rs);
}
if (fGenerateJavadoc) {
String string = CodeGeneration.getSetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fField.getElementName(), ASTNodes.asString(type), fArgName, StubUtility.getBaseName(fField),
lineDelimiter);
if (string != null) {
Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
result.setJavadoc(javadoc);
}
}
return result;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
ImportRewriteContext context=new ContextSensitiveImportRewriteContext(targetTypeDecl, getImportRewrite());
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
SimpleName newNameNode= getNewName(rewrite);
decl.setConstructor(isConstructor());
addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());
ArrayList<String> takenNames= new ArrayList<>();
addNewTypeParameters(rewrite, takenNames, decl.typeParameters(), context);
decl.setName(newNameNode);
IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
takenNames.add(declaredFields[i].getName());
}
String bodyStatement= ""; //$NON-NLS-1$
boolean isAbstractMethod= Modifier.isAbstract(decl.getModifiers()) || (fSenderBinding.isInterface() && !Modifier.isStatic(decl.getModifiers()) && !Modifier.isDefault(decl.getModifiers()));
if (!isConstructor()) {
Type returnType= getNewMethodType(rewrite, context);
decl.setReturnType2(returnType);
boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
if (!isAbstractMethod && !isVoid) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
}
}
addNewParameters(rewrite, takenNames, decl.parameters(), context);
addNewExceptions(rewrite, decl.thrownExceptionTypes(), context);
Block body= null;
if (!isAbstractMethod && !Flags.isAbstract(decl.getModifiers())) {
body= ast.newBlock();
if (bodyStatement.length() > 0) {
ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement,
ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(getCompilationUnit().getResource());
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string = CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null,
String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private MethodDeclaration createHashCodeMethod() throws CoreException {
MethodDeclaration hashCodeMethod= fAst.newMethodDeclaration();
hashCodeMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PUBLIC));
hashCodeMethod.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
hashCodeMethod.setConstructor(false);
hashCodeMethod.setReturnType2(fAst.newPrimitiveType(PrimitiveType.INT));
Block body= fAst.newBlock();
hashCodeMethod.setBody(body);
// PRIME NUMBER
VariableDeclarationFragment frag= fAst.newVariableDeclarationFragment();
frag.setName(fAst.newSimpleName(VARIABLE_NAME_PRIME));
frag.setInitializer(fAst.newNumberLiteral(PRIME_NUMBER));
VariableDeclarationStatement primeNumberDeclaration= fAst.newVariableDeclarationStatement(frag);
primeNumberDeclaration.modifiers().add(fAst.newModifier(ModifierKeyword.FINAL_KEYWORD));
primeNumberDeclaration.setType(fAst.newPrimitiveType(PrimitiveType.INT));
body.statements().add(primeNumberDeclaration);
// RESULT
VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
fragment.setName(fAst.newSimpleName(VARIABLE_NAME_RESULT));
VariableDeclarationStatement resultDeclaration= fAst.newVariableDeclarationStatement(fragment);
resultDeclaration.setType(fAst.newPrimitiveType(PrimitiveType.INT));
body.statements().add(resultDeclaration);
if (needsNoSuperCall(fType, METHODNAME_HASH_CODE, new ITypeBinding[0])) {
fragment.setInitializer(fAst.newNumberLiteral(INITIAL_HASHCODE_VALUE));
} else {
SuperMethodInvocation invoc= fAst.newSuperMethodInvocation();
invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
fragment.setInitializer(invoc);
}
if (isMemberType()) {
body.statements().add(createAddOuterHashCode());
}
for (int i= 0; i < fFields.length; i++) {
if (fFields[i].getType().isPrimitive()) {
Statement[] sts= createAddSimpleHashCode(fFields[i].getType(), new IHashCodeAccessProvider() {
public Expression getThisAccess(String name) {
return getThisAccessForHashCode(name);
}
}, fFields[i].getName(), false);
for (int j= 0; j < sts.length; j++) {
body.statements().add(sts[j]);
}
} else if (fFields[i].getType().isArray())
body.statements().add(createAddArrayHashCode(fFields[i]));
else
body.statements().add(createAddQualifiedHashCode(fFields[i]));
}
// the last return:
ReturnStatement endReturn= fAst.newReturnStatement();
endReturn.setExpression(fAst.newSimpleName(VARIABLE_NAME_RESULT));
body.statements().add(endReturn);
// method comment
if (fSettings != null) {
ITypeBinding object= fAst.resolveWellKnownType(JAVA_LANG_OBJECT);
IMethodBinding[] objms= object.getDeclaredMethods();
IMethodBinding objectMethod= null;
for (int i= 0; i < objms.length; i++) {
if (objms[i].getName().equals(METHODNAME_HASH_CODE) && objms[i].getParameterTypes().length == 0)
objectMethod= objms[i];
}
createMethodComment(hashCodeMethod, objectMethod);
}
return hashCodeMethod;
}
private void createIntermediaryMethod() throws CoreException {
CompilationUnitRewrite imRewrite= getCachedCURewrite(fIntermediaryType.getCompilationUnit());
AST ast= imRewrite.getAST();
MethodDeclaration intermediary= ast.newMethodDeclaration();
// Intermediary class is non-anonymous
AbstractTypeDeclaration type= (AbstractTypeDeclaration)typeToDeclaration(fIntermediaryType, imRewrite.getRoot());
// Name
intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));
// Flags
List<IExtendedModifier> modifiers= intermediary.modifiers();
if (!fIntermediaryType.isInterface()) {
modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
}
modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
// Parameters
String targetParameterName= StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());
ImportRewriteContext context= new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
if (!isStaticTarget()) {
// Add first param
SingleVariableDeclaration parameter= imRewrite.getAST().newSingleVariableDeclaration();
Type t= imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
if (fIntermediaryFirstParameterType.isGenericType()) {
ParameterizedType parameterized= imRewrite.getAST().newParameterizedType(t);
ITypeBinding[] typeParameters= fIntermediaryFirstParameterType.getTypeParameters();
for (int i= 0; i < typeParameters.length; i++)
parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
t= parameterized;
}
parameter.setType(t);
parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
intermediary.parameters().add(parameter);
}
// Add other params
copyArguments(intermediary, imRewrite);
// Add type parameters of declaring type (and enclosing types)
if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);
// Add type params of method
copyTypeParameters(intermediary, imRewrite);
// Return type
intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));
// Exceptions
copyExceptions(intermediary, imRewrite);
// Body
MethodInvocation invocation= imRewrite.getAST().newMethodInvocation();
invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
if (isStaticTarget()) {
Type importedType= imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
} else {
invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
}
copyInvocationParameters(invocation, ast);
Statement call= encapsulateInvocation(intermediary, invocation);
final Block body= imRewrite.getAST().newBlock();
body.statements().add(call);
intermediary.setBody(body);
// method comment
ICompilationUnit targetCU= imRewrite.getCu();
if (StubUtility.doAddComments(targetCU.getJavaProject())) {
String comment= CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
if (comment != null) {
Javadoc javadoc= (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
intermediary.setJavadoc(javadoc);
}
}
// Add the completed method to the intermediary type:
ChildListPropertyDescriptor typeBodyDeclarationsProperty= typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());
ListRewrite bodyDeclarationsListRewrite= imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite
.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
}
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
Assert.isNotNull(delegate);
Assert.isNotNull(delegatingField);
Assert.isNotNull(settings);
AST ast= rewrite.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
decl.setName(ast.newSimpleName(delegate.getName()));
decl.setConstructor(false);
createTypeParameters(imports, context, ast, delegate, decl);
decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));
List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);
createThrownExceptions(decl, delegate, imports, context, ast);
Block body= ast.newBlock();
decl.setBody(body);
String delimiter= StubUtility.getLineDelimiterUsed(unit);
Statement statement= null;
MethodInvocation invocation= ast.newMethodInvocation();
invocation.setName(ast.newSimpleName(delegate.getName()));
List<Expression> arguments= invocation.arguments();
for (int i= 0; i < params.size(); i++)
arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
if (settings.useKeywordThis) {
FieldAccess access= ast.newFieldAccess();
access.setExpression(ast.newThisExpression());
access.setName(ast.newSimpleName(delegatingField.getName()));
invocation.setExpression(access);
} else
invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
statement= ast.newExpressionStatement(invocation);
} else {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(invocation);
statement= returnStatement;
}
body.statements().add(statement);
ITypeBinding declaringType= delegatingField.getDeclaringClass();
if (declaringType == null) { // can be null for
return decl;
}
String qualifiedName= declaringType.getQualifiedName();
IPackageBinding packageBinding= declaringType.getPackage();
if (packageBinding != null) {
if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
qualifiedName= qualifiedName.substring(packageBinding.getName().length());
}
if (settings.createComments) {
/*
* TODO: have API for delegate method comments This is an inlined
* version of
* {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
*/
delegate= delegate.getMethodDeclaration();
String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
String linkToMethodName= delegate.getName();
String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
Type type= field.getType();
MethodDeclaration result= ast.newMethodDeclaration();
result.setName(ast.newSimpleName(fSetterName));
result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
if (fSetterMustReturnValue) {
result.setReturnType2((Type)rewriter.createCopyTarget(type));
}
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
result.parameters().add(param);
param.setName(ast.newSimpleName(fArgName));
param.setType((Type)rewriter.createCopyTarget(type));
List<Dimension> extraDimensions= DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter);
param.extraDimensions().addAll(extraDimensions);
Block block= ast.newBlock();
result.setBody(block);
String fieldAccess= createFieldAccess();
String body= CodeGeneration.getSetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fieldAccess, fArgName, lineDelimiter);
if (body != null) {
ASTNode setterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
block.statements().add(setterNode);
} else {
Assignment ass= ast.newAssignment();
ass.setLeftHandSide((Expression) rewriter.createStringPlaceholder(fieldAccess, ASTNode.QUALIFIED_NAME));
ass.setRightHandSide(ast.newSimpleName(fArgName));
block.statements().add(ass);
}
if (fSetterMustReturnValue) {
ReturnStatement rs= ast.newReturnStatement();
rs.setExpression(ast.newSimpleName(fArgName));
block.statements().add(rs);
}
if (fGenerateJavadoc) {
String string= CodeGeneration.getSetterComment(
fField.getCompilationUnit() , getTypeName(field.getParent()), fSetterName,
fField.getElementName(), ASTNodes.asString(type), fArgName,
StubUtility.getBaseName(fField),
lineDelimiter);
if (string != null) {
Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
result.setJavadoc(javadoc);
}
}
return result;
}