Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#is18OrHigher()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#is18OrHigher() . 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: RenameLocalVariableProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	initAST();
	if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local);
	}

	if (!Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, LambdaExpression.class)) {
		if (JavaModelUtil.is18OrHigher(fCu.getJavaProject())) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_initializers_and_lambda);
		}

		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers);
	}

	initNames();
	return new RefactoringStatus();
}
 
Example 2
Source File: IntroduceIndirectionInputPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IType chooseIntermediaryType() {
	IJavaProject proj= getIntroduceIndirectionRefactoring().getProject();

	if (proj == null)
		return null;

	IJavaElement[] elements= new IJavaElement[] { proj };
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);

	int elementKinds= JavaModelUtil.is18OrHigher(proj) ? IJavaSearchConstants.CLASS_AND_INTERFACE : IJavaSearchConstants.CLASS;
	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, elementKinds);

	dialog.setTitle(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class);
	dialog.setMessage(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class_long);

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example 3
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	initAST();
	if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local);

	if (!Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class)
			&& !Checks.isDeclaredIn(fTempDeclarationNode, LambdaExpression.class)) {
		if (JavaModelUtil.is18OrHigher(fCu.getJavaProject()))
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_initializers_and_lambda);

		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers);
	}

	initNames();
	return new RefactoringStatus();
}
 
Example 4
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkMoveToInterface() throws JavaModelException {
	//could be more clever and make field final if it is only written once...
	boolean is18OrHigher= JavaModelUtil.is18OrHigher(fDestinationType.getJavaProject());
	RefactoringStatus result= new RefactoringStatus();
	boolean declaringIsInterface= getDeclaringType().isInterface();
	if (declaringIsInterface && is18OrHigher)
		return result;
	String moveMembersMsg= is18OrHigher ? RefactoringCoreMessages.MoveMembersRefactoring_only_public_static_18 : RefactoringCoreMessages.MoveMembersRefactoring_only_public_static;
	for (int i= 0; i < fMembersToMove.length; i++) {
		if (declaringIsInterface && !(fMembersToMove[i] instanceof IMethod) && !is18OrHigher) {
			// moving from interface to interface is OK, unless method is moved to pre-18
		} else if (!canMoveToInterface(fMembersToMove[i], is18OrHigher)) {
			result.addError(moveMembersMsg, JavaStatusContext.create(fMembersToMove[i]));
		} else if (!Flags.isPublic(fMembersToMove[i].getFlags()) && !declaringIsInterface) {
			result.addWarning(RefactoringCoreMessages.MoveMembersRefactoring_member_will_be_public, JavaStatusContext.create(fMembersToMove[i]));
		}
	}
	return result;
}
 
Example 5
Source File: TypeAnnotationRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from
 * <code>node</code>'s <code>childListProperty</code>.
 * <p>
 * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER}
 * the latter is ignored, because this is implied by the former and creates no ambiguity.</p>
 *
 * @param node ASTNode
 * @param childListProperty child list property
 * @param rewrite rewrite that removes the nodes
 * @param editGroup the edit group in which to collect the corresponding text edits, or null if
 *            ungrouped
 */
public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) {
	CompilationUnit root= (CompilationUnit) node.getRoot();
	if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) {
		return;
	}
	ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty);
	@SuppressWarnings("unchecked")
	List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty);
	for (ASTNode child : children) {
		if (child instanceof Annotation) {
			Annotation annotation= (Annotation) child;
			if (isPureTypeAnnotation(annotation)) {
				listRewrite.remove(child, editGroup);
			}
		}
	}
}
 
Example 6
Source File: JavaDocLocations.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException {
	buf.append(meth.getElementName());

	/*
	 * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs.
	 * This breaks all clients that directly create such URLs.
	 * We can't know what format is required, so we just guess by the project's compiler compliance.
	 */
	boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject());
	buf.append(is18OrHigher ? '-' : '(');
	String[] params = meth.getParameterTypes();
	IType declaringType = meth.getDeclaringType();
	boolean isVararg = Flags.isVarargs(meth.getFlags());
	int lastParam = params.length - 1;
	for (int i = 0; i <= lastParam; i++) {
		if (i != 0) {
			buf.append(is18OrHigher ? "-" : ", "); //$NON-NLS-1$ //$NON-NLS-2$
		}
		String curr = Signature.getTypeErasure(params[i]);
		String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType);
		if (fullName == null) { // e.g. a type parameter "QE;"
			fullName = Signature.toString(Signature.getElementType(curr));
		}
		if (fullName != null) {
			buf.append(fullName);
			int dim = Signature.getArrayCount(curr);
			if (i == lastParam && isVararg) {
				dim--;
			}
			while (dim > 0) {
				buf.append(is18OrHigher ? ":A" : "[]"); //$NON-NLS-1$ //$NON-NLS-2$
				dim--;
			}
			if (i == lastParam && isVararg) {
				buf.append("..."); //$NON-NLS-1$
			}
		}
	}
	buf.append(is18OrHigher ? '-' : ')');
}
 
Example 7
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isMoveStaticAvailable(final IMember member) throws JavaModelException {
	if (!member.exists()) {
		return false;
	}
	final int type = member.getElementType();
	if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE) {
		return false;
	}
	if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) {
		return false;
	}
	final IType declaring = member.getDeclaringType();
	if (declaring == null) {
		return false;
	}
	if (!Checks.isAvailable(member)) {
		return false;
	}
	if (type == IJavaElement.METHOD && declaring.isInterface()) {
		boolean is18OrHigher = JavaModelUtil.is18OrHigher(member.getJavaProject());
		if (!is18OrHigher || !Flags.isStatic(member.getFlags())) {
			return false;
		}
	}
	if (type == IJavaElement.METHOD && !JdtFlags.isStatic(member)) {
		return false;
	}
	if (type == IJavaElement.METHOD && ((IMethod) member).isConstructor()) {
		return false;
	}
	if (type == IJavaElement.TYPE && !JdtFlags.isStatic(member)) {
		return false;
	}
	if (!declaring.isInterface() && !JdtFlags.isStatic(member)) {
		return false;
	}
	return true;
}
 
Example 8
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isMoveStaticAvailable(final IMember member) throws JavaModelException {
	if (!member.exists())
		return false;
	final int type= member.getElementType();
	if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE)
		return false;
	if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE)
		return false;
	final IType declaring= member.getDeclaringType();
	if (declaring == null)
		return false;
	if (!Checks.isAvailable(member))
		return false;
	if (type == IJavaElement.METHOD && declaring.isInterface()) {
		boolean is18OrHigher= JavaModelUtil.is18OrHigher(member.getJavaProject());
		if (!is18OrHigher || !Flags.isStatic(member.getFlags()))
			return false;
	}
	if (type == IJavaElement.METHOD && !JdtFlags.isStatic(member))
		return false;
	if (type == IJavaElement.METHOD && ((IMethod) member).isConstructor())
		return false;
	if (type == IJavaElement.TYPE && !JdtFlags.isStatic(member))
		return false;
	if (!declaring.isInterface() && !JdtFlags.isStatic(member))
		return false;
	return true;
}
 
Example 9
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param fullyQualifiedTypeName the fully qualified name of the intermediary method
 * @return status for type name. Use {@link #setIntermediaryMethodName(String)} to check for overridden methods.
 */
public RefactoringStatus setIntermediaryTypeName(String fullyQualifiedTypeName) {
	IType target= null;

	try {
		if (fullyQualifiedTypeName.length() == 0)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_type_not_selected_error);

		// find type (now including secondaries)
		target= getProject().findType(fullyQualifiedTypeName, new NullProgressMonitor());
		if (target == null || !target.exists())
			return RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.IntroduceIndirectionRefactoring_type_does_not_exist_error, BasicElementLabels.getJavaElementName(fullyQualifiedTypeName)));
		if (target.isAnnotation())
			return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_annotation);
		if (target.isInterface() && !(JavaModelUtil.is18OrHigher(target.getJavaProject()) && JavaModelUtil.is18OrHigher(getProject())))
			return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_on_interface);
	} catch (JavaModelException e) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_unable_determine_declaring_type);
	}

	if (target.isReadOnly())
		return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_readonly);

	if (target.isBinary())
		return RefactoringStatus.createErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_binary);

	fIntermediaryType= target;

	return new RefactoringStatus();
}
 
Example 10
Source File: JavaDocLocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException {
	buf.append(meth.getElementName());

	/*
	 * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs.
	 * This breaks all clients that directly create such URLs.
	 * We can't know what format is required, so we just guess by the project's compiler compliance.
	 */
	boolean is18OrHigher= JavaModelUtil.is18OrHigher(meth.getJavaProject());
	buf.append(is18OrHigher ? '-' : '(');
	String[] params= meth.getParameterTypes();
	IType declaringType= meth.getDeclaringType();
	boolean isVararg= Flags.isVarargs(meth.getFlags());
	int lastParam= params.length - 1;
	for (int i= 0; i <= lastParam; i++) {
		if (i != 0) {
			buf.append(is18OrHigher ? "-" : ", "); //$NON-NLS-1$ //$NON-NLS-2$
		}
		String curr= Signature.getTypeErasure(params[i]);
		String fullName= JavaModelUtil.getResolvedTypeName(curr, declaringType);
		if (fullName == null) { // e.g. a type parameter "QE;"
			fullName= Signature.toString(Signature.getElementType(curr));
		}
		if (fullName != null) {
			buf.append(fullName);
			int dim= Signature.getArrayCount(curr);
			if (i == lastParam && isVararg) {
				dim--;
			}
			while (dim > 0) {
				buf.append(is18OrHigher ? ":A" : "[]"); //$NON-NLS-1$ //$NON-NLS-2$
				dim--;
			}
			if (i == lastParam && isVararg) {
				buf.append("..."); //$NON-NLS-1$
			}
		}
	}
	buf.append(is18OrHigher ? '-' : ')');
}
 
Example 11
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static LambdaExpressionsFix createConvertToLambdaFix(ClassInstanceCreation cic) {
	CompilationUnit root= (CompilationUnit) cic.getRoot();
	if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject()))
		return null;

	if (!LambdaExpressionsFix.isFunctionalAnonymous(cic))
		return null;

	CreateLambdaOperation op= new CreateLambdaOperation(Collections.singletonList(cic));
	return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, root, new CompilationUnitRewriteOperation[] { op });
}
 
Example 12
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNullityAnnotationTypesProposals(ICompilationUnit cu, Name node, Collection<ICommandAccess> proposals) throws CoreException {
	ASTNode parent= node.getParent();
	boolean isAnnotationName= parent instanceof Annotation && ((Annotation) parent).getTypeNameProperty() == node.getLocationInParent();
	if (!isAnnotationName) {
		boolean isImportName= parent instanceof ImportDeclaration && ImportDeclaration.NAME_PROPERTY == node.getLocationInParent();
		if (!isImportName)
			return;
	}
	
	final IJavaProject javaProject= cu.getJavaProject();
	String name= node.getFullyQualifiedName();
	
	String nullityAnnotation= null;
	String[] annotationNameOptions= { JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME };
	Hashtable<String, String> defaultOptions= JavaCore.getDefaultOptions();
	for (String annotationNameOption : annotationNameOptions) {
		String annotationName= javaProject.getOption(annotationNameOption, true);
		if (! annotationName.equals(defaultOptions.get(annotationNameOption)))
			return;
		if (JavaModelUtil.isMatchingName(name, annotationName)) {
			nullityAnnotation= annotationName;
		}
	}
	if (nullityAnnotation == null)
		return;
	if (javaProject.findType(defaultOptions.get(annotationNameOptions[0])) != null)
		return;
	String version= JavaModelUtil.is18OrHigher(javaProject) ? "2" : "[1.1.0,2.0.0)"; //$NON-NLS-1$ //$NON-NLS-2$
	Bundle[] annotationsBundles= JavaPlugin.getDefault().getBundles("org.eclipse.jdt.annotation", version); //$NON-NLS-1$
	if (annotationsBundles == null)
		return;
	
	if (! cu.getJavaProject().getProject().hasNature("org.eclipse.pde.PluginNature")) //$NON-NLS-1$
		addCopyAnnotationsJarProposal(cu, node, nullityAnnotation, annotationsBundles[0], proposals);
}
 
Example 13
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 14
Source File: NewMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private int evaluateModifiers(ASTNode targetTypeDecl) {
	if (getSenderBinding().isAnnotation()) {
		return 0;
	}
	boolean isTargetInterface= getSenderBinding().isInterface();
	if (isTargetInterface && !JavaModelUtil.is18OrHigher(getCompilationUnit().getJavaProject())) {
		// only abstract methods are allowed for interface present in less than Java 1.8
		return getInterfaceMethodModifiers(targetTypeDecl, true);
	}
	ASTNode invocationNode= getInvocationNode();
	if (invocationNode instanceof MethodInvocation) {
		int modifiers= 0;
		Expression expression= ((MethodInvocation)invocationNode).getExpression();
		if (expression != null) {
			if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
				modifiers |= Modifier.STATIC;
			}
		} else if (ASTResolving.isInStaticContext(invocationNode)) {
			modifiers |= Modifier.STATIC;
		}
		ASTNode node= ASTResolving.findParentType(invocationNode);
		boolean isParentInterface= node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();
		if (isTargetInterface || isParentInterface) {
			if (expression == null && !targetTypeDecl.equals(node)) {
				modifiers|= Modifier.STATIC;
				if (isTargetInterface) {
					modifiers|= getInterfaceMethodModifiers(targetTypeDecl, false);
				} else {
					modifiers|= Modifier.PROTECTED;
				}
			} else if (modifiers == Modifier.STATIC) {
				modifiers= getInterfaceMethodModifiers(targetTypeDecl, false) | Modifier.STATIC;
			} else {
				modifiers= getInterfaceMethodModifiers(targetTypeDecl, true);
			}
		} else if (targetTypeDecl.equals(node)) {
			modifiers |= Modifier.PRIVATE;
		} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
			modifiers |= Modifier.PROTECTED;
			if (ASTResolving.isInStaticContext(node) && expression == null) {
				modifiers |= Modifier.STATIC;
			}
		} else {
			modifiers |= Modifier.PUBLIC;
		}
		return modifiers;
	}
	return Modifier.PUBLIC;
}
 
Example 15
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
boolean isValidDestination(ASTNode node) {
	boolean isInterface = node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();
	return !(node instanceof AnnotationTypeDeclaration) && !(isInterface && !JavaModelUtil.is18OrHigher(fCUnit.getJavaProject()));
}
 
Example 16
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean is18OrHigherInterface(ITypeBinding binding) {
	if (!binding.isInterface() || binding.isAnnotation())
		return false;
	IJavaElement javaElement= binding.getJavaElement();
	return javaElement != null && JavaModelUtil.is18OrHigher(javaElement.getJavaProject());
}
 
Example 17
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
boolean isValidDestination(ASTNode node) {
	boolean isInterface= node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();
	return !(node instanceof AnnotationTypeDeclaration) &&
			!(isInterface && !JavaModelUtil.is18OrHigher(fCUnit.getJavaProject()));
}
 
Example 18
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}