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

The following examples show how to use org.eclipse.jdt.core.dom.MethodDeclaration#modifiers() . 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: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean hasNullAnnotation(MethodDeclaration decl) {
	List<IExtendedModifier> modifiers= decl.modifiers();
	String nonnull= NullAnnotationsFix.getNonNullAnnotationName(decl.resolveBinding().getJavaElement(), false);
	String nullable= NullAnnotationsFix.getNullableAnnotationName(decl.resolveBinding().getJavaElement(), false);
	for (Object mod : modifiers) {
		if (mod instanceof Annotation) {
			Name annotationName= ((Annotation) mod).getTypeName();
			String fullyQualifiedName= annotationName.getFullyQualifiedName();
			if (annotationName.isSimpleName() ? nonnull.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nonnull))
				return true;
			if (annotationName.isSimpleName() ? nullable.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nullable))
				return true;
		}
	}
	return false;
}
 
Example 2
Source File: MethodDiff.java    From apidiff with MIT License 5 votes vote down vote up
/**
 * Returning method full name. [access modifier + return + name + (parameters list)]
 * @param methodVersion
 * @return
 */
private String getFullNameMethod(MethodDeclaration methodVersion){
	String nameMethod = "";
	if(methodVersion != null){
		String modifiersMethod = (methodVersion.modifiers() != null) ? (StringUtils.join(methodVersion.modifiers(), " ") + " ") : " ";
		String returnMethod = (methodVersion.getReturnType2() != null) ? (methodVersion.getReturnType2().toString() + " ") : "";
		String parametersMethod = (methodVersion.parameters() != null) ? StringUtils.join(methodVersion.parameters(), ", ") : " ";
		nameMethod = modifiersMethod + returnMethod + methodVersion.getName() + "(" + parametersMethod + ")";
	}
	return nameMethod;
}
 
Example 3
Source File: ChangePublicToProtectedResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Modifier getPublicModifier(MethodDeclaration method) {
    List<?> list = method.modifiers();
    for (Object o : list) {
        if (o.getClass().equals(Modifier.class)) {
            Modifier mdf = (Modifier) o;
            if (mdf.getKeyword().equals(PUBLIC_KEYWORD)) {
                return mdf;
            }
        }

    }
    return null;
}
 
Example 4
Source File: MethodUtils.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
public static boolean hasOverrideAnnotation(final MethodDeclaration node) {
	final List modifiers = node.modifiers();
	for (final Object mod : modifiers) {
		final IExtendedModifier modifier = (IExtendedModifier) mod;
		if (modifier.isAnnotation()) {
			final Annotation annotation = (Annotation) modifier;
			if (annotation.getTypeName().toString().equals("Override")) {
				return true;
			}
		}
	}
	return false;
}
 
Example 5
Source File: MethodUtils.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean hasOverrideAnnotation(final MethodDeclaration node) {
	final List modifiers = node.modifiers();
	for (final Object mod : modifiers) {
		final IExtendedModifier modifier = (IExtendedModifier) mod;
		if (modifier.isAnnotation()) {
			final Annotation annotation = (Annotation) modifier;
			if (annotation.getTypeName().toString().equals("Override")) {
				return true;
			}
		}
	}
	return false;
}
 
Example 6
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
private void setPublicModifierToSourceMethod(IMethodBinding methodBinding, TypeDeclaration sourceTypeDeclaration) {
	MethodDeclaration[] methodDeclarations = sourceTypeDeclaration.getMethods();
	for(MethodDeclaration methodDeclaration : methodDeclarations) {
		if(methodDeclaration.resolveBinding().isEqualTo(methodBinding)) {
			CompilationUnit sourceCompilationUnit = RefactoringUtility.findCompilationUnit(methodDeclaration);
			ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
			ListRewrite modifierRewrite = sourceRewriter.getListRewrite(methodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
			Modifier publicModifier = methodDeclaration.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
			boolean modifierFound = false;
			List<IExtendedModifier> modifiers = methodDeclaration.modifiers();
			for(IExtendedModifier extendedModifier : modifiers) {
				if(extendedModifier.isModifier()) {
					Modifier modifier = (Modifier)extendedModifier;
					if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PUBLIC_KEYWORD)) {
						modifierFound = true;
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PRIVATE_KEYWORD)) {
						modifierFound = true;
						modifierRewrite.replace(modifier, publicModifier, null);
						updateAccessModifier(sourceRewriter, sourceCompilationUnit);
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PROTECTED_KEYWORD)) {
						modifierFound = true;
						IPackageBinding targetTypeDeclarationPackageBinding = this.targetTypeDeclaration.resolveBinding().getPackage();
						IPackageBinding typeDeclarationPackageBinding = sourceTypeDeclaration.resolveBinding().getPackage();
						if(targetTypeDeclarationPackageBinding != null && typeDeclarationPackageBinding != null &&
								!targetTypeDeclarationPackageBinding.isEqualTo(typeDeclarationPackageBinding)) {
							modifierRewrite.replace(modifier, publicModifier, null);
							updateAccessModifier(sourceRewriter, sourceCompilationUnit);
						}
					}
				}
			}
			if(!modifierFound) {
				modifierRewrite.insertFirst(publicModifier, null);
				updateAccessModifier(sourceRewriter, sourceCompilationUnit);
			}
		}
	}
}
 
Example 7
Source File: MethodUtils.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean hasOverrideAnnotation(final MethodDeclaration node) {
	final List modifiers = node.modifiers();
	for (final Object mod : modifiers) {
		final IExtendedModifier modifier = (IExtendedModifier) mod;
		if (modifier.isAnnotation()) {
			final Annotation annotation = (Annotation) modifier;
			if (annotation.getTypeName().toString().equals("Override")) {
				return true;
			}
		}
	}
	return false;
}
 
Example 8
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary changes to create the delegate method with the
 * original method body.
 *
 * @param document
 *            the buffer containing the source of the source compilation
 *            unit
 * @param declaration
 *            the method declaration to use as source
 * @param rewrite
 *            the ast rewrite to use for the copy of the method body
 * @param rewrites
 *            the compilation unit rewrites
 * @param adjustments
 *            the map of elements to visibility adjustments
 * @param status
 *            the refactoring status
 * @param monitor
 *            the progress monitor to display progress
 * @throws CoreException
 *             if an error occurs
 */
protected void createMethodCopy(IDocument document, MethodDeclaration declaration, ASTRewrite rewrite, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, RefactoringStatus status, IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	Assert.isNotNull(rewrites);
	Assert.isNotNull(adjustments);
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getCompilationUnit());
	try {
		rewrite.set(declaration, MethodDeclaration.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), null);
		boolean same= false;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
				same= true;
			final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
			ModifierRewrite modifierRewrite= ModifierRewrite.create(rewrite, declaration);
			if (JdtFlags.isDefaultMethod(binding) && getTargetType().isClass()) {
				// Remove 'default' modifier and add 'public' visibility
				modifierRewrite.setVisibility(Modifier.PUBLIC, null);
				modifierRewrite.setModifiers(Modifier.NONE, Modifier.DEFAULT, null);
			} else if (!JdtFlags.isDefaultMethod(binding) && getTargetType().isInterface()) {
				// Remove visibility modifiers and add 'default'
				modifierRewrite.setModifiers(Modifier.DEFAULT, Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE, null);
			} else if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue())
					&& MemberVisibilityAdjustor.needsVisibilityAdjustments(fMethod, keyword, adjustments)) {
				final MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(fMethod, keyword, RefactoringStatus.createStatus(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(fMethod), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(fMethod), null, RefactoringStatusEntry.NO_CODE, null));
				modifierRewrite.setVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), null);
				adjustment.setNeedsRewriting(false);
				adjustments.put(fMethod, adjustment);
			}
		}
		for (IExtendedModifier modifier : (List<IExtendedModifier>) declaration.modifiers()) {
			if (modifier.isAnnotation()) {
				Annotation annotation= (Annotation) modifier;
				ITypeBinding typeBinding= annotation.resolveTypeBinding();
				if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.Override")) { //$NON-NLS-1$
					rewrite.remove(annotation, null);
				}
			}
		}
		createMethodArguments(rewrites, rewrite, declaration, adjustments, status);
		createMethodTypeParameters(rewrite, declaration, status);
		createMethodComment(rewrite, declaration);
		createMethodBody(rewriter, rewrite, declaration);
	} finally {
		if (fMethod.getCompilationUnit().equals(getTargetType().getCompilationUnit()))
			rewriter.clearImportRewrites();
	}
}
 
Example 9
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 10
Source File: TypeVisitor.java    From repositoryminer with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public boolean visit(MethodDeclaration node) {
	AbstractMethod method = new AbstractMethod();
	method.setConstructor(node.isConstructor());
	method.setVarargs(node.isVarargs());

	StringBuilder builder = null;
	builder = new StringBuilder();
	builder.append(node.getName().getIdentifier()).append("(");

	List<AbstractParameter> params = new ArrayList<>();
	for (SingleVariableDeclaration var : (List<SingleVariableDeclaration>) node.parameters()) {
		IVariableBinding varBind = var.resolveBinding();
		AbstractParameter param = new AbstractParameter(varBind.getType().getQualifiedName(), varBind.getName());
		params.add(param);
		builder.append(param.getType() + ",");
	}

	if (builder.substring(builder.length() - 1).equals(",")) {
		builder.replace(builder.length() - 1, builder.length(), ")");
	} else {
		builder.append(")");
	}

	method.setName(builder.toString());
	method.setParameters(params);
	verifyAccessorMethod(method);

	List<String> throwsList = new ArrayList<String>();
	List<Type> types = node.thrownExceptionTypes();
	for (Type type : types) {
		throwsList.add(type.toString());
	}
	method.setThrownsExceptions(throwsList);

	List<String> modifiers = new ArrayList<String>();
	for (Object modifier : node.modifiers()) {
		modifiers.add(modifier.toString());
	}
	method.setModifiers(modifiers);

	if (node.getBody() != null) {
		MethodVisitor visitor = new MethodVisitor();
		node.getBody().accept(visitor);
		method.setMaxDepth(visitor.getMaxDepth());
		method.setStatements(visitor.getStatements());
	} else {
		method.setStatements(new ArrayList<AbstractStatement>());
	}

	if (node.getReturnType2() != null) {
		ITypeBinding bind = node.getReturnType2().resolveBinding();
		if (bind != null)
		method.setReturnType(bind.getQualifiedName());
	}

	method.setStartPosition(node.getStartPosition());
	method.setEndPosition(node.getStartPosition() + node.getLength() - 1);
	
	methods.add(method);
	return true;
}