Java Code Examples for org.eclipse.jdt.core.dom.MethodDeclaration#setName()

The following examples show how to use org.eclipse.jdt.core.dom.MethodDeclaration#setName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateAsyncMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
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;
}
 
Example 3
Source File: StagedBuilderWithMethodDefiniationCreatorFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public MethodDeclaration createNewWithMethod(AST ast, BuilderField builderField,
        StagedBuilderProperties nextStage) {
    String fieldName = builderField.getBuilderFieldName();
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
    builderMethod.setReturnType2(ast.newSimpleType(ast.newName(nextStage.getInterfaceName())));
    builderMethod.parameters()
            .add(withMethodParameterCreatorFragment.createWithMethodParameter(ast, builderField.getFieldType(), fieldName));

    if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
        markerAnnotationAttacher.attachNonNull(ast, builderMethod);
    }
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    return builderMethod;
}
 
Example 4
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
}
 
Example 5
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 6
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
 	Assert.isTrue(! isDeclaredInAnonymousClass());
 	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent();
 	final MethodDeclaration[] constructors= getAllConstructors(declaration);
 	if (constructors.length == 0) {
 		AST ast= rewrite.getAST();
 		MethodDeclaration newConstructor= ast.newMethodDeclaration();
 		newConstructor.setConstructor(true);
 		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
 		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
 		newConstructor.setJavadoc(getNewConstructorComment(rewrite));
 		newConstructor.setBody(ast.newBlock());

 		addFieldInitializationToConstructor(rewrite, newConstructor);

 		int insertionIndex= computeInsertIndexForNewConstructor(declaration);
rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
 	} else {
 		for (int index= 0; index < constructors.length; index++) {
             if (shouldInsertTempInitialization(constructors[index]))
                 addFieldInitializationToConstructor(rewrite, constructors[index]);
         }
 	}
 }
 
Example 7
Source File: CreateSyncMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example 8
Source File: DefaultConstructorAppender.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private MethodDeclaration createConstructor(CompilationUnitModificationDomain domain) {
    AST ast = domain.getAst();

    Block emptyBody = ast.newBlock();
    MethodDeclaration defaultConstructor = ast.newMethodDeclaration();
    defaultConstructor.setBody(emptyBody);
    defaultConstructor.setConstructor(true);
    defaultConstructor.setName(ast.newSimpleName(domain.getOriginalType().getName().toString()));
    defaultConstructor.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, defaultConstructor);
    }

    return defaultConstructor;
}
 
Example 9
Source File: StaticBuilderMethodSignatureGeneratorFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public MethodDeclaration create(AST ast, String builderMethodName, String builderName) {
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderMethodName));
    addGenerateAnnotationIfNeeded(ast, builderMethod);
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
    builderMethod.setReturnType2(ast.newSimpleType(ast.newName(builderName)));
    return builderMethod;
}
 
Example 10
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: RegularBuilderCopyInstanceConstructorAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private MethodDeclaration createCopyConstructorWithBody(AST ast, TypeDeclaration builderType, TypeDeclaration originalType, String parameterName,
        Block body) {
    MethodDeclaration copyConstructor = ast.newMethodDeclaration();
    copyConstructor.setBody(body);
    copyConstructor.setConstructor(true);
    copyConstructor.setName(ast.newSimpleName(builderType.getName().toString()));
    copyConstructor.modifiers().add(ast.newModifier(PRIVATE_KEYWORD));
    copyConstructor.parameters().add(createParameter(ast, originalType, parameterName));
    return copyConstructor;
}
 
Example 13
Source File: PublicConstructorWithMandatoryFieldsAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private MethodDeclaration createPublicConstructor(AST ast, Block body, TypeDeclaration builderType, List<BuilderField> fields) {
    MethodDeclaration publicConstructorMethod = ast.newMethodDeclaration();
    publicConstructorMethod.setBody(body);
    publicConstructorMethod.setConstructor(true);
    publicConstructorMethod.setName(ast.newSimpleName(builderType.getName().toString()));
    publicConstructorMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    for (BuilderField field : fields) {
        SingleVariableDeclaration parameter = createParameter(ast, field.getFieldType(), field.getBuilderFieldName());
        publicConstructorMethod.parameters().add(parameter);
    }

    return publicConstructorMethod;

}
 
Example 14
Source File: PrivateConstructorAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void addEmptyPrivateConstructor(AST ast, TypeDeclaration builderType) {
    MethodDeclaration privateConstructorMethod = ast.newMethodDeclaration();
    privateConstructorMethod.setBody(ast.newBlock());
    privateConstructorMethod.setConstructor(true);
    privateConstructorMethod.setName(ast.newSimpleName(builderType.getName().toString()));
    privateConstructorMethod.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
    builderType.bodyDeclarations().add(privateConstructorMethod);
}
 
Example 15
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite,
    ImportRewrite importRewrite, boolean addComments) throws CoreException {
  AST ast = astRewrite.getAST();
  MethodDeclaration methodDecl = ast.newMethodDeclaration();

  // Method is named after the resource it accesses
  methodDecl.setName(ast.newSimpleName(getMethodName()));

  // Method return type is a ResourcePrototype subtype
  ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName());
  Type resourceType = importRewrite.addImport(resourceTypeBinding, ast);
  methodDecl.setReturnType2(resourceType);

  // Add @Source annotation if necessary
  String sourceAnnotationValue = getSourceAnnotationValue(clientBundle);
  if (sourceAnnotationValue != null) {
    // Build the annotation
    SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation();
    sourceAnnotation.setTypeName(ast.newName("Source"));
    StringLiteral annotationValue = ast.newStringLiteral();
    annotationValue.setLiteralValue(sourceAnnotationValue);
    sourceAnnotation.setValue(annotationValue);

    // Add the annotation to the method
    ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty();
    ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers);
    modifiersRewriter.insertFirst(sourceAnnotation, null);
  }

  return methodDecl;
}
 
Example 16
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
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));
	}
 
Example 17
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
	decl.setName(ast.newSimpleName(typeBinding.getName()));
	decl.setConstructor(true);

	List<SingleVariableDeclaration> parameters= decl.parameters();
	if (superConstructor != null) {
		createTypeParameters(imports, context, ast, superConstructor, decl);

		createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);

		createThrownExceptions(decl, superConstructor, imports, context, ast);
	}

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	if (superConstructor != null) {
		SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
		SingleVariableDeclaration varDecl= null;
		for (Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();) {
			varDecl= iterator.next();
			invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
		}
		body.statements().add(invocation);
	}

	List<String> prohibited= new ArrayList<String>();
	for (final Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();)
		prohibited.add(iterator.next().getName().getIdentifier());
	String param= null;
	List<String> list= new ArrayList<String>(prohibited);
	String[] excluded= null;
	for (int i= 0; i < variableBindings.length; i++) {
		SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
		var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
		excluded= new String[list.size()];
		list.toArray(excluded);
		param= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(param);
		var.setName(ast.newSimpleName(param));
		parameters.add(var);
	}

	list= new ArrayList<String>(prohibited);
	for (int i= 0; i < variableBindings.length; i++) {
		excluded= new String[list.size()];
		list.toArray(excluded);
		final String paramName= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(paramName);
		final String fieldName= variableBindings[i].getName();
		Expression expression= null;
		if (paramName.equals(fieldName) || settings.useKeywordThis) {
			FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fieldName));
			expression= access;
		} else
			expression= ast.newSimpleName(fieldName);
		Assignment assignment= ast.newAssignment();
		assignment.setLeftHandSide(expression);
		assignment.setRightHandSide(ast.newSimpleName(paramName));
		assignment.setOperator(Assignment.Operator.ASSIGN);
		body.statements().add(ast.newExpressionStatement(assignment));
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 18
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
	decl.setName(ast.newSimpleName(type));
	decl.setConstructor(true);

	createTypeParameters(imports, context, ast, binding, decl);

	List<SingleVariableDeclaration> parameters= createParameters(unit.getJavaProject(), imports, context, ast, binding, null, decl);

	createThrownExceptions(decl, binding, imports, context, ast);

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);
	String bodyStatement= ""; //$NON-NLS-1$
	if (!omitSuperForDefConst || !parameters.isEmpty()) {
		SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
		SingleVariableDeclaration varDecl= null;
		for (Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();) {
			varDecl= iterator.next();
			invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
		}
		bodyStatement= ASTNodes.asFormattedString(invocation, 0, delimiter, unit.getJavaProject().getOptions(true));
	}

	if (todo) {
		String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), true, bodyStatement, delimiter);
		if (placeHolder != null) {
			ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	} else {
		ReturnStatement statementNode= (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement, ASTNode.RETURN_STATEMENT);
		body.statements().add(statementNode);
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
Source File: AbstractMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement= (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}