Java Code Examples for org.eclipse.jdt.core.IType#getMethod()

The following examples show how to use org.eclipse.jdt.core.IType#getMethod() . 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: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method returns an IMethod element from the given method and declaring type bindings. However,
 * unlike {@link Util#findMethod(IType, char[], String[], boolean)} , this does not require an IType to get 
 * the IMethod element.
 * @param method the given method binding
 * @param signatures the type signatures of the method arguments
 * @param declaringClass the binding of the method's declaring class
 * @return an IMethod corresponding to the method binding given, or null if none is found.
 */
public IJavaElement findMethodFromBinding(MethodBinding method, String[] signatures, ReferenceBinding declaringClass) {
	IType foundType = this.resolveType(declaringClass.qualifiedPackageName(), declaringClass.qualifiedSourceName(), NameLookup.ACCEPT_CLASSES & NameLookup.ACCEPT_INTERFACES);
	if (foundType != null) {
		if (foundType instanceof BinaryType) {
			try {
				return Util.findMethod(foundType, method.selector, signatures, method.isConstructor());
			} catch (JavaModelException e) {
				return null;
			}
		} else {
			return foundType.getMethod(new String(method.selector), signatures);
		}
	}
	return null;
}
 
Example 2
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private IMethod findJavaMethod(IType type) {
	// Locate the method from its signature.
	//
	String[] parameterTypes = Signature.getParameterTypes(new BindingKey("Lx;.x(" + signature + ")").toSignature());
	IMethod javaMethod = type.getMethod(name, parameterTypes);

	// If the method doesn't exist and this is a nested type...
	//
	if (!javaMethod.exists() && type.getDeclaringType() != null) {
		// This special case handles what appears to be a JDT bug 
		// that sometimes it knows when there are implicit constructor arguments for nested types and sometimes it doesn't.
		// Infer one more initial parameter type and locate the method based on that.
		//
		String[] augmented = new String[parameterTypes.length + 1];
		System.arraycopy(parameterTypes, 0, augmented, 1, parameterTypes.length);
		String first = Signature.createTypeSignature(type.getDeclaringType().getFullyQualifiedName(), true);
		augmented[0] = first;
		javaMethod = type.getMethod(name, augmented);
	}
	return javaMethod;
}
 
Example 3
Source File: LaunchPipelineShortcut.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private static LaunchableResource toLaunchableResource(IResource resource) {
  if (resource == null) {
    return null;
  }
  IJavaElement javaElement = resource.getAdapter(IJavaElement.class);
  if (javaElement != null && javaElement.exists() && javaElement instanceof ICompilationUnit) {
    ICompilationUnit compilationUnit = (ICompilationUnit) javaElement;
    IType javaType = compilationUnit.findPrimaryType();
    if (javaType == null) {
      return null;
    }
    IMethod mainMethod = javaType.getMethod(
        "main", new String[] {Signature.createTypeSignature("String[]", false)});
    return new LaunchableResource(resource, mainMethod, javaType);
  }
  return new LaunchableResource(resource);
}
 
Example 4
Source File: SourceMapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void exitAbstractMethod(int declarationEnd) {
	if (this.typeDepth >= 0) {
		IType currentType = this.types[this.typeDepth];
		SourceRange sourceRange =
			new SourceRange(
				this.memberDeclarationStart[this.typeDepth],
				declarationEnd - this.memberDeclarationStart[this.typeDepth] + 1);
		IMethod method = currentType.getMethod(
				this.memberName[this.typeDepth],
				convertTypeNamesToSigs(this.methodParameterTypes[this.typeDepth]));
		setSourceRange(
			method,
			sourceRange,
			this.memberNameRange[this.typeDepth]);
		setMethodParameterNames(
			method,
			this.methodParameterNames[this.typeDepth]);
	}
}
 
Example 5
Source File: AnnotationAtttributeProposalInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Resolves the member described by the receiver and returns it if found.
 * Returns <code>null</code> if no corresponding member can be found.
 *
 * @return the resolved member or <code>null</code> if none is found
 * @throws JavaModelException if accessing the java model fails
 */
@Override
protected IMember resolveMember() throws JavaModelException {
	char[] declarationSignature= fProposal.getDeclarationSignature();
	// for synthetic fields on arrays, declaration signatures may be null
	// TODO remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed
	if (declarationSignature == null)
		return null;
	String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature));
	IType type= fJavaProject.findType(typeName);
	if (type != null) {
		String name= String.valueOf(fProposal.getName());
		IMethod method= type.getMethod(name, CharOperation.NO_STRINGS);
		if (method.exists())
			return method;
	}
	return null;
}
 
Example 6
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Resolve the binary method
 *
 * fix for 1FWFT6Q
 */
protected void acceptBinaryMethod(
		IType type,
		char[] selector,
		char[][] parameterPackageNames,
		char[][] parameterTypeNames,
		String[] parameterSignatures,
		char[][] typeParameterNames,
		char[][][] typeParameterBoundNames,
		char[] uniqueKey,
		boolean isConstructor) {
	IMethod method= type.getMethod(new String(selector), parameterSignatures);

	if (method.exists()) {
		if (typeParameterNames != null && typeParameterNames.length != 0) {
			IMethod[] methods = type.findMethods(method);
			if (methods != null && methods.length > 1) {
				for (int i = 0; i < methods.length; i++) {
					if (areTypeParametersCompatible(methods[i], typeParameterNames, typeParameterBoundNames)) {
						acceptBinaryMethod(type, method, uniqueKey, isConstructor);
					}
				}
				return;
			}
		}
		acceptBinaryMethod(type, method, uniqueKey, isConstructor);
	}
}
 
Example 7
Source File: JavaElementFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void consumeMethod(char[] selector, char[] signature) {
	if (!(this.element instanceof IType)) return;
	String[] parameterTypes = Signature.getParameterTypes(new String(signature));
	IType type = (IType) this.element;
	IMethod method = type.getMethod(new String(selector), parameterTypes);
	IMethod[] methods = type.findMethods(method);
	if (methods.length > 0)
		this.element = methods[0];
}
 
Example 8
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IJavaElement createMethodHandle(IType type, String methodName, String[] parameterTypeSignatures) {
	IMethod methodHandle = type.getMethod(methodName, parameterTypeSignatures);
	if (methodHandle instanceof SourceMethod) {
		while (this.methodHandles.contains(methodHandle)) {
			((SourceMethod) methodHandle).occurrenceCount++;
		}
	}
	this.methodHandles.add(methodHandle);
	return methodHandle;
}
 
Example 9
Source File: RenameTypeWizardSimilarElementsPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus validateSettings() {
	final String name= fNameField.getText();
	if (name.length() == 0) {
		return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_empty);
	}
	IStatus status= JavaConventionsUtil.validateIdentifier(name, fElementToEdit);
	if (status.matches(IStatus.ERROR))
		return status;
	if (!Checks.startsWithLowerCase(name))
		return new StatusInfo(IStatus.WARNING, RefactoringMessages.RenameTypeWizardSimilarElementsPage_name_should_start_lowercase);

	if (fElementToEdit instanceof IMember && ((IMember) fElementToEdit).getDeclaringType() != null) {
		IType type= ((IMember) fElementToEdit).getDeclaringType();
		if (fElementToEdit instanceof IField) {
			final IField f= type.getField(name);
			if (f.exists())
				return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_field_exists);
		}
		if (fElementToEdit instanceof IMethod) {
			final IMethod m= type.getMethod(name, ((IMethod) fElementToEdit).getParameterTypes());
			if (m.exists())
				return new StatusInfo(IStatus.ERROR, RefactoringMessages.RenameTypeWizardSimilarElementsPage_method_exists);
		}
	}

	// cannot check local variables; no .getLocalVariable(String) in IMember

	return StatusInfo.OK_STATUS;
}
 
Example 10
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean canBeAccessedFrom(final IMember member, final IType target, final ITypeHierarchy hierarchy) throws JavaModelException {
	if (super.canBeAccessedFrom(member, target, hierarchy)) {
		if (target.isInterface())
			return true;
		if (target.equals(member.getDeclaringType()))
			return true;
		if (target.equals(member))
			return true;
		if (member instanceof IMethod) {
			final IMethod method= (IMethod) member;
			final IMethod stub= target.getMethod(method.getElementName(), method.getParameterTypes());
			if (stub.exists())
				return true;
		}
		if (member.getDeclaringType() == null) {
			if (!(member instanceof IType))
				return false;
			if (JdtFlags.isPublic(member))
				return true;
			if (!JdtFlags.isPackageVisible(member))
				return false;
			if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment()))
				return true;
			final IType type= member.getDeclaringType();
			if (type != null)
				return hierarchy.contains(type);
			return false;
		}
		final IType declaringType= member.getDeclaringType();
		if (!canBeAccessedFrom(declaringType, target, hierarchy))
			return false;
		if (declaringType.equals(getDeclaringType()))
			return false;
		return true;
	}
	return false;
}
 
Example 11
Source File: MethodGeneratorImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
private Set<IMethod> getExcludedMethods(IType objectClass, LinkedHashSet<MethodSkeleton<U>> methodSkeletons)
        throws Exception {
    Set<IMethod> excludedMethods = new HashSet<IMethod>();
    for (MethodSkeleton<U> methodSkeleton : methodSkeletons) {
        IMethod excludedMethod = objectClass.getMethod(methodSkeleton.getMethodName(),
                methodSkeleton.getMethodArguments(objectClass));
        if (excludedMethod.exists()) {
            excludedMethods.add(excludedMethod);
        }
    }
    return excludedMethods;
}
 
Example 12
Source File: GWTMemberRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testGetEditDescriptionForMethod() {
  GWTMemberRefactoringSupport support = new GWTMemberRefactoringSupport();

  IType refactorTest = refactorTestClass.getCompilationUnit().getType(
      "RefactorTest");
  IMethod method = refactorTest.getMethod("getMagicNumber", new String[0]);
  support.setOldElement(method);
  assertEquals("Update method reference", support.getEditDescription());
}
 
Example 13
Source File: JavaQueryParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testElementSearch() throws CoreException {
  IType cu1Type = getTestType1();
  IJavaElement element;

  // Search for type references
  element = cu1Type;
  Match[] expected = new Match[] {
      createWindowsTestMatch(665, 41), createWindowsTestMatch(735, 41),
      createWindowsTestMatch(840, 41), createWindowsTestMatch(947, 41),
      createWindowsTestMatch(1125, 41), createWindowsTestMatch(1207, 41),
      createWindowsTestMatch(1297, 41), createWindowsTestMatch(1419, 41),
      createWindowsTestMatch(1545, 41), createWindowsTestMatch(1619, 41)};
  assertSearchMatches(expected, createQuery(element));

  // Search for field references
  element = cu1Type.getField("keith");
  assertSearchMatch(createWindowsTestMatch(990, 5), createQuery(element));

  // Search for method references
  element = cu1Type.getMethod("getNumber", NO_PARAMS);
  assertSearchMatch(createWindowsTestMatch(1588, 9), createQuery(element));

  // Search for constructor references
  element = cu1Type.getType("InnerSub").getMethod("InnerSub",
      new String[] {"QString;"});
  assertSearchMatch(createWindowsTestMatch(892, 3), createQuery(element));

  // Search for package references (unsupported)
  element = cu1Type.getPackageFragment();
  assertSearchMatches(NO_MATCHES, createQuery(element));
}
 
Example 14
Source File: JavadocContentTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMethodJavadoc() throws Exception {
	IType type = project.findType("org.sample.TestJavadoc");
	assertNotNull(type);
	IMethod method = type.getMethod("foo", new String[0]);
	assertNotNull(method);
	MarkedString signature = HoverInfoProvider.computeSignature(method);
	assertEquals("String org.sample.TestJavadoc.foo()", signature.getValue());
	MarkedString javadoc = HoverInfoProvider.computeJavadoc(method);
	assertEquals("Foo method", javadoc.getValue());
}
 
Example 15
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Resolves the method described by the receiver and returns it if found.
 * Returns <code>null</code> if no corresponding member can be found.
 *
 * @param proposal
 *            - completion proposal
 * @param javaProject
 *            - Java project
 *
 * @return the resolved method or <code>null</code> if none is found
 * @throws JavaModelException
 *             if accessing the java model fails
 */

public static IMethod resolveMethod(CompletionProposal proposal, IJavaProject javaProject) throws JavaModelException {
	char[] declarationSignature = proposal.getDeclarationSignature();
	String typeName = SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature));
	IType type = javaProject.findType(typeName);
	if (type != null) {
		String name = String.valueOf(proposal.getName());
		if (proposal.getKind() == CompletionProposal.ANNOTATION_ATTRIBUTE_REF) {
			IMethod method = type.getMethod(name, CharOperation.NO_STRINGS);
			if (method.exists()) {
				return method;
			} else {
				return null;
			}
		}
		char[] signature = proposal.getSignature();
		if (proposal instanceof InternalCompletionProposal) {
			Binding binding = ((InternalCompletionProposal) proposal).getBinding();
			if (binding instanceof MethodBinding) {
				MethodBinding methodBinding = (MethodBinding) binding;
				MethodBinding original = methodBinding.original();
				if (original != binding) {
					signature = Engine.getSignature(original);
				}
			}
		}
		String[] parameters = Signature.getParameterTypes(String.valueOf(SignatureUtil.fix83600(signature)));
		for (int i = 0; i < parameters.length; i++) {
			parameters[i] = SignatureUtil.getLowerBound(parameters[i]);
		}
		boolean isConstructor = proposal.isConstructor();

		return JavaModelUtil.findMethod(name, parameters, isConstructor, type);
	}

	return null;
}
 
Example 16
Source File: GWTRenameParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean initialize(Object element) {
  if (element instanceof IType || element instanceof IMethod
      || element instanceof IField) {
    GWTRefactoringSupport support = getRefactoringSupport();

    IMember oldMember = (IMember) element;
    support.setOldElement(oldMember);

    try {
      /*
       * We can't trust our RenameArgument's getNewName() to always return the
       * correct new name. When the user sets the new name in the Rename
       * refactoring dialog, clicks Next to go to the Preview page, then
       * clicks Back and changes the new name, getNewName() returns the
       * original name, not the updated one. This appears to be a bug in the
       * JDT, which affects other built-in rename participants such as
       * BreakpointRenameTypeParticipant. It does not affect the core JDT
       * refactorings, though, since they are executed directly from
       * JavaRenameRefactoring and not as loaded rename participants.
       * 
       * The workaround here is to instead go directly to the refactoring
       * processor and query it for the new element, which will have the right
       * name.
       * 
       * TODO: file this as a JDT bug?
       */
      JavaRenameProcessor processor = getRenameProcessor();
      IJavaElement newElement = (IJavaElement) processor.getNewElement();
      IType declaringType = oldMember.getDeclaringType();
      String newElementName = newElement.getElementName();
      /*
       * Compute the new method by using the declaring type of the old method.
       * Otherwise when a RenameVirtualMethodProcessor instance is passed in,
       * we will end up looking at the topmost declaration of the method
       * instead of the one we actually want because
       * RenameVirtualMethodProcessor.getNewElement() actually points to the
       * topmost declaration.
       */
      if (element instanceof IField) {
        newElement = declaringType.getField(newElementName);
      } else if (element instanceof IMethod) {
        IMethod method = (IMethod) newElement;
        newElement = declaringType.getMethod(newElementName,
            method.getParameterTypes());
      } else {
        assert (element instanceof IType);
      }

      support.setNewElement(newElement);
      support.setUpdateReferences(getArguments().getUpdateReferences());

      return true;
    } catch (CoreException e) {
      GWTPluginLog.logError(e);
    }
  }

  return false;
}
 
Example 17
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IMethod getMethodInWorkingCopy(IMethod method, String elementName, IType typeWc) {
	String[] paramTypeSignatures= method.getParameterTypes();
	return typeWc.getMethod(elementName, paramTypeSignatures);
}
 
Example 18
Source File: GenericRefactoringHandleTransplanter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected IMethod transplantHandle(IType parent, IMethod element) {
	return parent.getMethod(element.getElementName(), element.getParameterTypes());
}
 
Example 19
Source File: GenericRefactoringHandleTransplanter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
protected IMethod transplantHandle(IType parent, IMethod element) {
	return parent.getMethod(element.getElementName(), element.getParameterTypes());
}
 
Example 20
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private IMethod getMethodInWorkingCopy(IMethod method, String elementName, IType typeWc) {
	String[] paramTypeSignatures= method.getParameterTypes();
	return typeWc.getMethod(elementName, paramTypeSignatures);
}