Java Code Examples for org.eclipse.jdt.core.dom.IMethodBinding#getJavaElement()

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding#getJavaElement() . 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: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setIgnoreMethodBodies(true);
	IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
	parser.setProject(javaProject);
	IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
	ITypeBinding typeBinding = (ITypeBinding) bindings[0];
	IMethodBinding[] methods = typeBinding.getDeclaredMethods();
	for(IMethodBinding method: methods) {
		if (method.isConstructor()) {
			IMethod element = (IMethod) method.getJavaElement();
			if (element.exists()) {
				String[] parameterNames = element.getParameterNames();
				if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
					return true;
				}
			} else {
				return false;
			}
		}
	}
	return false;
}
 
Example 2
Source File: APIMethodData.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public void initByIMethodBinding(IMethodBinding mBinding) {
	IMethod iMethod = (IMethod) mBinding.getJavaElement();
	try {
		key = iMethod.getKey().substring(0, iMethod.getKey().indexOf("("))
				+ iMethod.getSignature();
		projectName = mBinding.getJavaElement().getJavaProject()
				.getElementName();
	} catch (Exception e) {
		projectName = "";
	}
	packageName = mBinding.getDeclaringClass().getPackage().getName();
	className = mBinding.getDeclaringClass().getName();
	name = mBinding.getName();

	parameters = new ArrayList<>();
	ITypeBinding[] parameterBindings = mBinding.getParameterTypes();
	for (int i = 0; i < parameterBindings.length; i++) {
		parameters.add(parameterBindings[i].getName());
	}
}
 
Example 3
Source File: MethodsSourcePositionComparator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
	try {
		IMethod firstMethod= (IMethod)firstMethodBinding.getJavaElement();
		IMethod secondMethod= (IMethod)secondMethodBinding.getJavaElement();
		if (firstMethod == null || secondMethod == null) {
			return 0;
		}
		ISourceRange firstSourceRange= firstMethod.getSourceRange();
		ISourceRange secondSourceRange= secondMethod.getSourceRange();

		if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) {
			return firstMethod.getElementName().compareTo(secondMethod.getElementName());
		} else {
			return firstSourceRange.getOffset() - secondSourceRange.getOffset();
		}
	} catch (JavaModelException e) {
		return 0;
	}
}
 
Example 4
Source File: OverrideIndicatorManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Opens and reveals the defining method.
 */
public void open() {
	CompilationUnit ast= SharedASTProvider.getAST(fJavaElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
	if (ast != null) {
		ASTNode node= ast.findDeclaringNode(fAstNodeKey);
		if (node instanceof MethodDeclaration) {
			try {
				IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
				IMethodBinding definingMethodBinding= Bindings.findOverriddenMethod(methodBinding, true);
				if (definingMethodBinding != null) {
					IJavaElement definingMethod= definingMethodBinding.getJavaElement();
					if (definingMethod != null) {
						JavaUI.openInEditor(definingMethod, true, true);
						return;
					}
				}
			} catch (CoreException e) {
				ExceptionHandler.handle(e, JavaEditorMessages.OverrideIndicatorManager_open_error_title, JavaEditorMessages.OverrideIndicatorManager_open_error_messageHasLogEntry);
				return;
			}
		}
	}
	String title= JavaEditorMessages.OverrideIndicatorManager_open_error_title;
	String message= JavaEditorMessages.OverrideIndicatorManager_open_error_message;
	MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
 
Example 5
Source File: NewAsyncRemoteServiceInterfaceCreationWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public static List<IMethodBinding> computeSyncMethodsThatNeedAsyncVersions(
    ITypeBinding syncTypeBinding, ITypeBinding asyncTypeBinding) {
  // Compute all overridable methods on the sync interface
  List<IMethodBinding> overridableSyncMethods = computeOverridableMethodsForInterface(syncTypeBinding);

  // Remove sync methods that would override existing methods in the
  // async hierarchy
  List<IMethodBinding> remainingMethods = new ArrayList<IMethodBinding>();
  for (IMethodBinding overridableSyncMethod : overridableSyncMethods) {
    IMethod syncMethod = (IMethod) overridableSyncMethod.getJavaElement();
    String[] asyncParameterTypes = RemoteServiceUtilities.computeAsyncParameterTypes(overridableSyncMethod);
    if (Bindings.findMethodInHierarchy(asyncTypeBinding,
        syncMethod.getElementName(), asyncParameterTypes) != null) {
      // Don't add method that appear in the type hierarchy
      continue;
    }

    remainingMethods.add(overridableSyncMethod);
  }

  return remainingMethods;
}
 
Example 6
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	IBinding binding= getBinding(token);
	if (binding != null) {
		if (binding.isDeprecated())
			return true;
		if (binding instanceof IMethodBinding) {
			IMethodBinding methodBinding= (IMethodBinding) binding;
			if (methodBinding.isConstructor() && methodBinding.getJavaElement() == null) {
				ITypeBinding declaringClass= methodBinding.getDeclaringClass();
				if (declaringClass.isAnonymous()) {
					ITypeBinding[] interfaces= declaringClass.getInterfaces();
					if (interfaces.length > 0)
						return interfaces[0].isDeprecated();
					else
						return declaringClass.getSuperclass().isDeprecated();
				}
				return declaringClass.isDeprecated();
			}
		}
	}
	return false;
}
 
Example 7
Source File: MethodsSourcePositionComparator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
	try {
		IMethod firstMethod= (IMethod)firstMethodBinding.getJavaElement();
		IMethod secondMethod= (IMethod)secondMethodBinding.getJavaElement();
		if (firstMethod == null || secondMethod == null) {
			return 0;
		}
		ISourceRange firstSourceRange= firstMethod.getSourceRange();
		ISourceRange secondSourceRange= secondMethod.getSourceRange();

		if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) {
			return firstMethod.getElementName().compareTo(secondMethod.getElementName());
		} else {
			return firstSourceRange.getOffset() - secondSourceRange.getOffset();
		}
	} catch (JavaModelException e) {
		return 0;
	}
}
 
Example 8
Source File: MethodCallAnalyzer.java    From JDeodorant with MIT License 5 votes vote down vote up
private MethodDeclaration getInvokedMethodDeclaration(IMethodBinding methodBinding) {
	MethodDeclaration invokedMethodDeclaration = null;
	IMethod iMethod2 = (IMethod)methodBinding.getJavaElement();
	if(iMethod2 != null) {
		IClassFile methodClassFile = iMethod2.getClassFile();
		LibraryClassStorage instance = LibraryClassStorage.getInstance();
		CompilationUnit methodCompilationUnit = instance.getCompilationUnit(methodClassFile);
		Set<TypeDeclaration> methodTypeDeclarations = extractTypeDeclarations(methodCompilationUnit);
		for(TypeDeclaration methodTypeDeclaration : methodTypeDeclarations) {
			ITypeBinding methodTypeDeclarationBinding = methodTypeDeclaration.resolveBinding();
			if(methodTypeDeclarationBinding != null && (methodTypeDeclarationBinding.isEqualTo(methodBinding.getDeclaringClass()) ||
					methodTypeDeclarationBinding.getBinaryName().equals(methodBinding.getDeclaringClass().getBinaryName()))) {
				MethodDeclaration[] methodDeclarations2 = methodTypeDeclaration.getMethods();
				for(MethodDeclaration methodDeclaration2 : methodDeclarations2) {
					if(methodDeclaration2.resolveBinding().isEqualTo(methodBinding) ||
							equalSignature(methodDeclaration2.resolveBinding(), methodBinding)) {
						invokedMethodDeclaration = methodDeclaration2;
						break;
					}
				}
				if(invokedMethodDeclaration != null)
					break;
			}
		}
	}
	return invokedMethodDeclaration;
}
 
Example 9
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getBaseNameFromLocationInParent(Expression assignedExpression, List<Expression> arguments, IMethodBinding binding) {
	if (binding == null)
		return null;

	ITypeBinding[] parameterTypes= binding.getParameterTypes();
	if (parameterTypes.length != arguments.size()) // beware of guessed method bindings
		return null;

	int index= arguments.indexOf(assignedExpression);
	if (index == -1)
		return null;

	ITypeBinding expressionBinding= assignedExpression.resolveTypeBinding();
	if (expressionBinding != null && !expressionBinding.isAssignmentCompatible(parameterTypes[index]))
		return null;

	try {
		IJavaElement javaElement= binding.getJavaElement();
		if (javaElement instanceof IMethod) {
			IMethod method= (IMethod)javaElement;
			if (method.getOpenable().getBuffer() != null) { // avoid dummy names and lookup from Javadoc
				String[] parameterNames= method.getParameterNames();
				if (index < parameterNames.length) {
					return NamingConventions.getBaseName(NamingConventions.VK_PARAMETER, parameterNames[index], method.getJavaProject());
				}
			}
		}
	} catch (JavaModelException e) {
		// ignore
	}
	return null;
}
 
Example 10
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Search for all calls to the given <code>IMethodBinding</code> in the project
 * that contains the compilation unit <code>fCUHandle</code>.
 * @param methodBinding
 * @param pm
 * @param status
 * @return an array of <code>SearchResultGroup</code>'s that identify the search matches
 * @throws JavaModelException
 */
private SearchResultGroup[] searchForCallsTo(IMethodBinding methodBinding, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	IMethod method= (IMethod) methodBinding.getJavaElement();
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(createSearchPattern(method, methodBinding));
	engine.setFiltering(true, true);
	engine.setScope(createSearchScope(method, methodBinding));
	engine.setStatus(status);
	engine.searchPattern(new SubProgressMonitor(pm, 1));
	return (SearchResultGroup[]) engine.getResults();
}
 
Example 11
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SourceProvider resolveSourceProvider(RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) {
	CompilationUnit root= (CompilationUnit)invocation.getRoot();
	IMethodBinding methodBinding= Invocations.resolveBinding(invocation);
	if (methodBinding == null) {
		status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
		return null;
	}
	MethodDeclaration declaration= (MethodDeclaration)root.findDeclaringNode(methodBinding);
	if (declaration != null) {
		return new SourceProvider(typeRoot, declaration);
	}
	IMethod method= (IMethod)methodBinding.getJavaElement();
	if (method != null) {
		CompilationUnit methodDeclarationAstRoot;
		ICompilationUnit methodCu= method.getCompilationUnit();
		if (methodCu != null) {
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(methodCu, true);
		} else {
			IClassFile classFile= method.getClassFile();
			if (! JavaElementUtil.isSourceAvailable(classFile)) {
				String methodLabel= JavaElementLabels.getTextLabel(method, JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES);
				status.addFatalError(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel));
				return null;
			}
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(classFile, true);
		}
		ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey());
		if (node instanceof MethodDeclaration) {
			return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (MethodDeclaration) node);
		}
	}
	status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
	return null;
}
 
Example 12
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the method to inline, or null if the method could not be found or
 * {@link #checkInitialConditions(IProgressMonitor)} has not been called yet.
 *
 * @return the method, or <code>null</code>
 */
public IMethod getMethod() {
	if (fSourceProvider == null)
		return null;
	IMethodBinding binding= fSourceProvider.getDeclaration().resolveBinding();
	if (binding == null)
		return null;
	return (IMethod) binding.getJavaElement();
}
 
Example 13
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode findDeclaration(CompilationUnit root, ConstraintVariable cv) throws JavaModelException {

		if (fFieldBinding != null){
			IField f= (IField) fFieldBinding.getJavaElement();
			return ASTNodeSearchUtil.getFieldDeclarationNode(f, root);
		}

		if (cv instanceof ExpressionVariable){
			for (Iterator<ITypeConstraint> iter= fAllConstraints.iterator(); iter.hasNext();) {
				ITypeConstraint constraint= iter.next();
				if (constraint.isSimpleTypeConstraint()){
					SimpleTypeConstraint stc= (SimpleTypeConstraint)constraint;
					if (stc.isDefinesConstraint() && stc.getLeft().equals(cv)){
						ConstraintVariable right= stc.getRight();
						if (right instanceof TypeVariable){
							TypeVariable typeVariable= (TypeVariable)right;
							return NodeFinder.perform(root, typeVariable.getCompilationUnitRange().getSourceRange());
						}
					}
				}
			}
		} else if (cv instanceof ReturnTypeVariable) {
			ReturnTypeVariable rtv= (ReturnTypeVariable) cv;
			IMethodBinding mb= rtv.getMethodBinding();
			IMethod im= (IMethod) mb.getJavaElement();
			return ASTNodeSearchUtil.getMethodDeclarationNode(im, root);
		}
		return null;
	}
 
Example 14
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean checkOverriddenBinaryMethods() {
	if (fMethodBinding != null){
		Set<ITypeBinding> declaringSupertypes= getDeclaringSuperTypes(fMethodBinding);
		for (Iterator<ITypeBinding> iter= declaringSupertypes.iterator(); iter.hasNext();) {
			ITypeBinding superType= iter.next();
			IMethodBinding overriddenMethod= findMethod(fMethodBinding, superType);
			Assert.isNotNull(overriddenMethod);//because we asked for declaring types
			IMethod iMethod= (IMethod) overriddenMethod.getJavaElement();
			if (iMethod.isBinary()){
				return true;
			}
		}
	}
	return false;
}
 
Example 15
Source File: MoveHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static MoveDestinationsResponse getInstanceMethodDestinations(CodeActionParams params) {
	final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
	if (unit == null) {
		return new MoveDestinationsResponse("Cannot find the compilation unit associated with " + params.getTextDocument().getUri());
	}

	MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
	if (methodDeclaration == null) {
		return new MoveDestinationsResponse("The selected element is not a method.");
	}

	IMethodBinding methodBinding = methodDeclaration.resolveBinding();
	if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
		return new MoveDestinationsResponse("The selected element is not a method.");
	}

	IMethod method = (IMethod) methodBinding.getJavaElement();
	MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(method.getJavaProject().getProject()));
	Refactoring refactoring = new MoveRefactoring(processor);
	CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
	try {
		check.run(new NullProgressMonitor());
		if (check.getStatus().hasFatalError()) {
			return new MoveDestinationsResponse(check.getStatus().getMessageMatchingSeverity(RefactoringStatus.FATAL));
		}

		IVariableBinding[] possibleTargets = processor.getPossibleTargets();
		LspVariableBinding[] targets = Stream.of(possibleTargets).map(target -> new LspVariableBinding(target)).toArray(LspVariableBinding[]::new);
		return new MoveDestinationsResponse(targets);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.log(e);
	}

	return new MoveDestinationsResponse("Cannot find any target to move the method to.");
}
 
Example 16
Source File: NewAsyncRemoteServiceInterfaceCreationWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public static String createMethodContents(IType newType,
    ImportManagerAdapter imports, IMethodBinding overridableSyncMethod,
    boolean addComments) throws CoreException, JavaModelException {
  StringBuilder sb = new StringBuilder();

  IMethod syncMethod = (IMethod) overridableSyncMethod.getJavaElement();

  if (addComments) {
    String lineDelimiter = "\n"; // OK, since content is formatted afterwards

    // Don't go through CodeGeneration type since it can't deal with delegates
    String comment = StubUtility.getMethodComment(
        newType.getCompilationUnit(), newType.getFullyQualifiedName(),
        syncMethod.getElementName(), NO_STRINGS, NO_STRINGS,
        Signature.SIG_VOID, NO_STRINGS, syncMethod, true, lineDelimiter);
    if (comment != null) {
      sb.append(comment);
      sb.append(lineDelimiter);
    }
  }

  // Expand the type parameters
  ITypeParameter[] typeParameters = syncMethod.getTypeParameters();
  ITypeBinding[] typeParameterBindings = overridableSyncMethod.getTypeParameters();
  if (typeParameters.length > 0) {
    sb.append("<");
    for (int i = 0; i < typeParameters.length; ++i) {
      sb.append(typeParameters[i].getElementName());
      ITypeBinding typeParameterBinding = typeParameterBindings[i];
      ITypeBinding[] typeBounds = typeParameterBinding.getTypeBounds();
      if (typeBounds.length > 0) {
        sb.append(" extends ");
        for (int j = 0; j < typeBounds.length; ++j) {
          if (j != 0) {
            sb.append(" & ");
          }
          expandTypeBinding(typeBounds[j], sb, imports);
        }
      }
    }
    sb.append(">");
  }

  // Default to a void return type for the async method
  sb.append("void ");

  // Expand the method name
  sb.append(overridableSyncMethod.getName());

  // Expand the arguments
  sb.append("(");
  String[] parameterNames = syncMethod.getParameterNames();
  ITypeBinding[] parameterTypes = overridableSyncMethod.getParameterTypes();
  for (int i = 0; i < parameterNames.length; ++i) {
    if (i != 0) {
      sb.append(", ");
    }

    expandTypeBinding(parameterTypes[i], sb, imports);
    sb.append(" ");
    sb.append(parameterNames[i]);
  }

  if (parameterNames.length > 0) {
    sb.append(", ");
  }

  sb.append(imports.addImport(RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME));
  sb.append("<");
  ITypeBinding syncReturnType = overridableSyncMethod.getReturnType();
  if (syncReturnType.isPrimitive()) {
    String wrapperTypeName = JavaASTUtils.getWrapperTypeName(syncReturnType.getName());
    sb.append(imports.addImport(wrapperTypeName));
  } else {
    expandTypeBinding(syncReturnType, sb, imports);
  }
  sb.append("> ");
  sb.append(StringUtilities.computeUniqueName(parameterNames, "callback"));
  sb.append(");");

  return sb.toString();
}
 
Example 17
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean isMoveMethodAvailable(MethodDeclaration declaration) throws JavaModelException {
	IMethodBinding methodBinding = declaration.resolveBinding();
	IMethod method = methodBinding == null ? null : (IMethod) methodBinding.getJavaElement();
	return method != null && RefactoringAvailabilityTester.isMoveMethodAvailable(method);
}