org.eclipse.jdt.core.IMethod Java Examples

The following examples show how to use org.eclipse.jdt.core.IMethod. 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: CallHierarchyContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the default "expand with constructors" mode for the method wrapper. Does nothing if the
 * mode has already been set.
 * 
 * 
 * @param wrapper the caller method wrapper
 * @since 3.5
 */
static void ensureDefaultExpandWithConstructors(CallerMethodWrapper wrapper) {

	if (!wrapper.isExpandWithConstructorsSet()) {
		if (CallHierarchyContentProvider.canExpandWithConstructors(wrapper)) {
			IMethod method= (IMethod)wrapper.getMember();
			IType type= method.getDeclaringType();
			try {
				boolean withConstructors= false;
				if (type != null) {
					boolean anonymousPref= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.PREF_ANONYMOUS_EXPAND_WITH_CONSTRUCTORS);
					if (anonymousPref && type.isAnonymous()) {
						withConstructors= true;
					} else if (isInTheDefaultExpandWithConstructorList(method)) {
						withConstructors= true;
					}
				}
				wrapper.setExpandWithConstructors(withConstructors);
			} catch (JavaModelException e) {
				// ignore: expand mode will be off
			}
		}
	}

}
 
Example #2
Source File: RippleMethodFinder2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IMethod[] getAllRippleMethods(IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
	IMethod[] rippleMethods= findAllRippleMethods(pm, owner);
	if (fDeclarationToMatch == null)
		return rippleMethods;

	List<IMethod> rippleMethodsList= new ArrayList<IMethod>(Arrays.asList(rippleMethods));
	for (Iterator<IMethod> iter= rippleMethodsList.iterator(); iter.hasNext(); ) {
		Object match= fDeclarationToMatch.get(iter.next());
		if (match != null) {
			iter.remove();
			fBinaryRefs.add((SearchMatch) match);
		}
	}
	fDeclarationToMatch= null;
	return rippleMethodsList.toArray(new IMethod[rippleMethodsList.size()]);
}
 
Example #3
Source File: RippleMethodFinder2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IMethod[] getAllRippleMethods(IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
	IMethod[] rippleMethods= findAllRippleMethods(pm, owner);
	if (fDeclarationToMatch == null) {
		return rippleMethods;
	}

	List<IMethod> rippleMethodsList= new ArrayList<>(Arrays.asList(rippleMethods));
	for (Iterator<IMethod> iter= rippleMethodsList.iterator(); iter.hasNext(); ) {
		Object match= fDeclarationToMatch.get(iter.next());
		if (match != null) {
			iter.remove();
			fBinaryRefs.add((SearchMatch) match);
		}
	}
	fDeclarationToMatch= null;
	return rippleMethodsList.toArray(new IMethod[rippleMethodsList.size()]);
}
 
Example #4
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Reader findDocInHierarchy(IMethod method, boolean useAttachedJavadoc) throws JavaModelException {
	/*
	 * Catch ExternalJavaProject in which case
	 * no hierarchy can be built.
	 */
	if (!method.getJavaProject().exists()) {
		return null;
	}

	IType type= method.getDeclaringType();
	ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null);

	MethodOverrideTester tester= new MethodOverrideTester(type, hierarchy);

	IType[] superTypes= hierarchy.getAllSupertypes(type);
	for (IType curr : superTypes) {
		IMethod overridden= tester.findOverriddenMethodInType(curr, method);
		if (overridden != null) {
			Reader reader = getHTMLContentReader(overridden, false, useAttachedJavadoc);
			if (reader != null) {
				return reader;
			}
		}
	}
	return null;
}
 
Example #5
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void checkOverridden(RefactoringStatus status, IProgressMonitor pm) throws JavaModelException {
	pm.beginTask("", 9); //$NON-NLS-1$
	pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
	MethodDeclaration decl= fSourceProvider.getDeclaration();
	IMethod method= (IMethod) decl.resolveBinding().getJavaElement();
	if (method == null || Flags.isPrivate(method.getFlags())) {
		pm.worked(8);
		return;
	}
	IType type= method.getDeclaringType();
	ITypeHierarchy hierarchy= type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
	checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
	checkSuperClasses(status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
	checkSuperInterfaces(status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1));
	pm.setTaskName(""); //$NON-NLS-1$
}
 
Example #6
Source File: SignatureHelpHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private boolean isSameParameters(IMethod method1, IMethod method2) {
	if (method1 == null || method2 == null) {
		return false;
	}
	String[] params1 = method1.getParameterTypes();
	String[] params2 = method2.getParameterTypes();
	if (params2.length == params1.length) {
		for (int i = 0; i < params2.length; i++) {
			String t1 = Signature.getSimpleName(Signature.toString(params2[i]));
			String t2 = Signature.getSimpleName(Signature.toString(params1[i]));
			if (!t1.equals(t2)) {
				return false;
			}
		}
		return true;
	}
	return false;
}
 
Example #7
Source File: Jdt2Ecore.java    From sarl with Apache License 2.0 6 votes vote down vote up
private String extractDefaultValue(IMethod operation, IAnnotation annot)
		throws JavaModelException, IllegalArgumentException {
	IAnnotation annotation = annot;
	final Object value = annotation.getMemberValuePairs()[0].getValue();
	final String fieldId = (value == null) ? null : value.toString();
	if (!Strings.isNullOrEmpty(fieldId)) {
		final String fieldName = Utils.createNameForHiddenDefaultValueAttribute(fieldId);
		final IField field = operation.getDeclaringType().getField(fieldName);
		if (field != null) {
			annotation = getAnnotation(field, SarlSourceCode.class.getName());
			if (annotation != null) {
				return annotation.getMemberValuePairs()[0].getValue().toString();
			}
		}
	}
	return null;
}
 
Example #8
Source File: MethodGeneratorImplTest.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGenerateWithTwoMethodsAlreadyExists() throws Exception {
    LinkedHashSet<MethodSkeleton<MethodGenerationData>> methodSkeletons = mockGetMethodSkeletons(commandIdentifier,
            method1Skeleton, method2Skeleton);
    LinkedHashSet<StrategyIdentifier> possibleStrategies = mockGetPossibleStrategies(methodSkeletons,
            strategyIdentifier1);
    mockDialog(Collections.<IMethod> emptySet(), possibleStrategies);
    mockGetMethods(methodSkeletons, method1, method2);

    Set<IMethod> excludedMethods = new HashSet<IMethod>();
    excludedMethods.add(excludedMethod1);
    excludedMethods.add(excludedMethod2);
    when(excludedMethod1.exists()).thenReturn(true);
    when(excludedMethod2.exists()).thenReturn(true);
    when(objectClass.createMethod(METHOD1_FULL_METHOD, elementPosition, true, null))
            .thenReturn(newPositionAfterMethod1);
    when(objectClass.createMethod(METHOD2_FULL_METHOD, newPositionAfterMethod1, true, null))
            .thenReturn(newPositionAfterMethod2);
    when(dialogFactory.createDialog(parentShell, objectClass, excludedMethods, possibleStrategies))
            .thenReturn(testDialog);
    methodGenerator.generate(parentShell, objectClass, commandIdentifier);
    verify(javaUiCodeAppender, times(1)).revealInEditor(objectClass, newPositionAfterMethod2);
    verify(compilationUnit, times(1)).createImport(METHOD2_LIBRARY_2, null, null);
    verify(excludedMethod1, times(1)).delete(true, null);
    verify(excludedMethod2, times(1)).delete(true, null);
}
 
Example #9
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void acceptLocalMethodTypeParameter(TypeVariableBinding typeVariableBinding) {
	MethodBinding methodBinding = (MethodBinding)typeVariableBinding.declaringElement;
	IJavaElement res = findLocalElement(methodBinding.sourceStart());
	if(res != null && res.getElementType() == IJavaElement.METHOD) {
		IMethod method = (IMethod) res;

		ITypeParameter typeParameter = method.getTypeParameter(new String(typeVariableBinding.sourceName));
		if (typeParameter.exists()) {
			addElement(typeParameter);
			if(SelectionEngine.DEBUG){
				System.out.print("SELECTION - accept type parameter("); //$NON-NLS-1$
				System.out.print(typeParameter.toString());
				System.out.println(")"); //$NON-NLS-1$
			}
		}
	}
}
 
Example #10
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkRelatedMethods() throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	for (Iterator<IMethod> iter= fMethodsToRename.iterator(); iter.hasNext(); ) {
		IMethod method= iter.next();

		result.merge(Checks.checkIfConstructorName(method, getNewElementName(), method.getDeclaringType().getElementName()));

		String[] msgData= new String[]{BasicElementLabels.getJavaElementName(method.getElementName()), BasicElementLabels.getJavaElementName(method.getDeclaringType().getFullyQualifiedName('.'))};
		if (! method.exists()){
			result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData));
			continue;
		}
		if (method.isBinary())
			result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData));
		if (method.isReadOnly())
			result.addFatalError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData));
		if (JdtFlags.isNative(method))
			result.addError(Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData));
	}
	return result;
}
 
Example #11
Source File: JsniMethodBodyCompletionProposalComputer.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Proposes a JSNI method of the form <code>return this.property[x]</code> if
 * the java method has a single integral type parameter.
 */
private void maybeProposeIndexedPropertyRead(IJavaProject project,
    IMethod method, int invocationOffset, int indentationUnits,
    List<ICompletionProposal> proposals, String propertyName,
    String[] parameterNames, boolean isStatic, int numCharsFilled, 
    int numCharsToOverwrite) throws JavaModelException {
  if (parameterNames.length != 1) {
    return;
  }

  String indexParameterType = method.getParameterTypes()[0];
  if (isIndexType(indexParameterType)) {
    String expression = "return "
        + createJsIndexedPropertyReadExpression(propertyName,
            parameterNames[0], isStatic) + ";";

    String code = createJsniBlock(project, expression, indentationUnits);
    proposals.add(createProposal(method.getFlags(), code, invocationOffset,
        numCharsFilled, numCharsToOverwrite, expression));
  }
}
 
Example #12
Source File: JavaElementFinder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IJavaElement caseJvmConstructor(JvmConstructor object) {
	IJavaElement parent = getDeclaringTypeElement(object);
	if (parent instanceof IType) {
		IType type = (IType) parent;
		try {
			for(IMethod method: type.getMethods()) {
				if (method.isConstructor() && object.getParameters().size() == method.getNumberOfParameters()) {
					boolean match = doParametersMatch(object, method, type);
					if (match)
						return method;
				}
			}
		}
		catch (JavaModelException e) {
			return (isExactMatchOnly) ? null : parent;
		}
	}
	return (isExactMatchOnly) ? null : parent;
}
 
Example #13
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
final static IMethod[] hierarchyDeclaresMethodName(IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName) throws CoreException {
	try {
		Set<IMethod> result= new HashSet<>();
		IType type= method.getDeclaringType();
		IMethod foundMethod= Checks.findMethod(newName, method.getParameterTypes().length, false, type);
		if (foundMethod != null) {
			result.add(foundMethod);
		}
		IMethod[] foundInHierarchyClasses= classesDeclareMethodName(hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName);
		if (foundInHierarchyClasses != null) {
			result.addAll(Arrays.asList(foundInHierarchyClasses));
		}
		IType[] implementingClasses= hierarchy.getImplementingClasses(type);
		IMethod[] foundInImplementingClasses= classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName);
		if (foundInImplementingClasses != null) {
			result.addAll(Arrays.asList(foundInImplementingClasses));
		}
		return result.toArray(new IMethod[result.size()]);
	} finally {
		if (pm != null) {
			pm.done();
		}
	}
}
 
Example #14
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 #15
Source File: MainMethodSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	Object enclosingElement= match.getElement();
	if (enclosingElement instanceof IMethod) { // defensive code
		try {
			IMethod curr= (IMethod) enclosingElement;
			if (curr.isMainMethod()) {
				if (!considerExternalJars()) {
					IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(curr);
					if (root == null || root.isArchive()) {
						return;
					}
				}
				if (!considerBinaries() && curr.isBinary()) {
					return;
				}
				fResult.add(curr.getDeclaringType());
			}
		} catch (JavaModelException e) {
			JavaPlugin.log(e.getStatus());
		}
	}
}
 
Example #16
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds the first available attached Javadoc in the hierarchy of the given method.
 *
 * @param method the method
 * @return the inherited Javadoc from the Javadoc attachment, or <code>null</code> if none
 * @throws JavaModelException unexpected problem
 */
private static String findAttachedDocInHierarchy(final IMethod method) throws JavaModelException {
	IType type= method.getDeclaringType();
	ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(type);
	final MethodOverrideTester tester= SuperTypeHierarchyCache.getMethodOverrideTester(type);

	return (String) new InheritDocVisitor() {
		@Override
		public Object visit(IType currType) throws JavaModelException {
			IMethod overridden= tester.findOverriddenMethodInType(currType, method);
			if (overridden == null)
				return InheritDocVisitor.CONTINUE;

			if (overridden.getOpenable().getBuffer() == null) { // only if no source available
				//TODO: BaseURL for method can be wrong for attached Javadoc from overridden
				// (e.g. when overridden is from rt.jar). Fix would be to add baseURL here.
				String attachedJavadoc= overridden.getAttachedJavadoc(null);
				if (attachedJavadoc != null)
					return attachedJavadoc;
			}
			return CONTINUE;
		}
	}.visitInheritDoc(type, hierarchy);
}
 
Example #17
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addMethodDelegate(IMethod getter, String newName, CompilationUnitRewrite rewrite) throws JavaModelException {
	MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(getter, rewrite.getRoot());
	DelegateCreator creator= new DelegateMethodCreator();
	creator.setDeclareDeprecated(fDelegateDeprecation);
	creator.setDeclaration(declaration);
	creator.setNewElementName(newName);
	creator.setSourceRewrite(rewrite);
	creator.prepareDelegate();
	creator.createEdit();
}
 
Example #18
Source File: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected JvmConstructor getConstructorFromType(EObject context, Class<?> type, String constructor) {
	JvmConstructor result = super.getConstructorFromType(context, type, constructor);
	if (result != null) {
		IJavaElement found = elementFinder.findElementFor(result);
		assertEquals(IJavaElement.METHOD, found.getElementType());
		assertEquals(result.getSimpleName(), found.getElementName());
		IMethod foundMethod = (IMethod) found;
		assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
	}
	return result;
}
 
Example #19
Source File: PatchFixesHider.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static org.eclipse.jdt.core.dom.MethodDeclaration getRealMethodDeclarationNode(org.eclipse.jdt.core.IMethod sourceMethod, org.eclipse.jdt.core.dom.CompilationUnit cuUnit) throws JavaModelException {
	MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, cuUnit);
	if (isGenerated(methodDeclarationNode)) {
		IType declaringType = sourceMethod.getDeclaringType();
		Stack<IType> typeStack = new Stack<IType>();
		while (declaringType != null) {
			typeStack.push(declaringType);
			declaringType = declaringType.getDeclaringType();
		}
		
		IType rootType = typeStack.pop();
		org.eclipse.jdt.core.dom.AbstractTypeDeclaration typeDeclaration = findTypeDeclaration(rootType, cuUnit.types());
		while (!typeStack.isEmpty() && typeDeclaration != null) {
			typeDeclaration = findTypeDeclaration(typeStack.pop(), typeDeclaration.bodyDeclarations());
		}
		
		if (typeStack.isEmpty() && typeDeclaration != null) {
			String methodName = sourceMethod.getElementName();
			for (Object declaration : typeDeclaration.bodyDeclarations()) {
				if (declaration instanceof org.eclipse.jdt.core.dom.MethodDeclaration) {
					org.eclipse.jdt.core.dom.MethodDeclaration methodDeclaration = (org.eclipse.jdt.core.dom.MethodDeclaration) declaration;
					if (methodDeclaration.getName().toString().equals(methodName)) {
						return methodDeclaration;
					}
				}
			}
		}
	}
	return methodDeclarationNode;
}
 
Example #20
Source File: RenameFieldProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName) throws CoreException{
	RefactoringStatus result= new RefactoringStatus();
	IMethod accessor= JavaModelUtil.findMethod(newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType());
	if (accessor == null || !accessor.exists())
		return null;

	String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
			new String[]{JavaElementUtil.createMethodSignature(accessor), BasicElementLabels.getJavaElementName(fField.getDeclaringType().getFullyQualifiedName('.'))});
	result.addError(message, JavaStatusContext.create(accessor));
	return result;
}
 
Example #21
Source File: IntroduceParameterObjectAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	try {
		IMethod singleSelectedMethod= getSingleSelectedMethod(selection);
		if (!ActionUtil.isEditable(getShell(), singleSelectedMethod))
			return;
		run(singleSelectedMethod);
	} catch (CoreException e) {
		ExceptionHandler.handle(e, getShell(), ActionMessages.IntroduceParameterObjectAction_exceptiondialog_title,	ActionMessages.IntroduceParameterObjectAction_unexpected_exception);
	}
}
 
Example #22
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCloneable() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test4.java");
	IType testClass = cu.createType("public class Test4 implements Cloneable {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "clone()" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "equals", "clone", "toString", "finalize", "hashCode" }, methods);
}
 
Example #23
Source File: MoveInstanceMethodAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void run(ITextSelection selection, ICompilationUnit cu) throws JavaModelException {
	Assert.isNotNull(cu);
	Assert.isTrue(selection.getOffset() >= 0);
	Assert.isTrue(selection.getLength() >= 0);

	if (!ActionUtil.isEditable(fEditor, getShell(), cu))
		return;

	IMethod method= getMethod(cu, selection);
	if (method != null) {
		RefactoringExecutionStarter.startMoveMethodRefactoring(method, getShell());
	} else {
		MessageDialog.openInformation(getShell(), RefactoringMessages.MoveInstanceMethodAction_dialog_title, RefactoringMessages.MoveInstanceMethodAction_No_reference_or_declaration);
	}
}
 
Example #24
Source File: Jdt2EcoreTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Test
public void protectedMethod() throws JavaModelException {
	IType parentType = createITypeMock(false, "io.sarl.eclipse.tests.package1.Type1", null);
	IMethod method = createIMethodMock(parentType, "myFct", "boolean",
			new String[0], new String[0],
			Flags.AccProtected);

	IType type = createITypeMock(false, "io.sarl.eclipse.tests.package2.Type2", null);

	assertFalse(this.jdt2ecore.isVisible(this.jdt2ecore.toTypeFinder(this.project), type, method));
}
 
Example #25
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String[] suggestArgumentNames(IJavaProject project, IMethodBinding binding) {
	int nParams= binding.getParameterTypes().length;

	if (nParams > 0) {
		try {
			IMethod method= (IMethod)binding.getMethodDeclaration().getJavaElement();
			if (method != null) {
				String[] paramNames= method.getParameterNames();
				if (paramNames.length == nParams) {
					String[] namesArray= EMPTY;
					ArrayList<String> newNames= new ArrayList<String>(paramNames.length);
					// Ensure that the code generation preferences are respected
					for (int i= 0; i < paramNames.length; i++) {
						String curr= paramNames[i];
						String baseName= NamingConventions.getBaseName(NamingConventions.VK_PARAMETER, curr, method.getJavaProject());
						if (!curr.equals(baseName)) {
							// make the existing name the favorite
							newNames.add(curr);
						} else {
							newNames.add(suggestArgumentName(project, curr, namesArray));
						}
						namesArray= newNames.toArray(new String[newNames.size()]);
					}
					return namesArray;
				}
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	String[] names= new String[nParams];
	for (int i= 0; i < names.length; i++) {
		names[i]= "arg" + i; //$NON-NLS-1$
	}
	return names;
}
 
Example #26
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isPullUpAvailable(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;
	}
	if (!Checks.isAvailable(member)) {
		return false;
	}
	if (member instanceof IType) {
		if (!JdtFlags.isStatic(member) && !JdtFlags.isEnum(member) && !JdtFlags.isAnnotation(member)) {
			return false;
		}
	}
	if (member instanceof IMethod) {
		final IMethod method = (IMethod) member;
		if (method.isConstructor()) {
			return false;
		}
		if (JdtFlags.isNative(method)) {
			return false;
		}
		final IType declaring = method.getDeclaringType();
		if (declaring != null && declaring.isAnnotation()) {
			return false;
		}
	}
	return true;
}
 
Example #27
Source File: HierarchyInformationControl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getHeaderLabel(IJavaElement input) {
	if (input instanceof IMethod) {
		String[] args= { JavaElementLabels.getElementLabel(input.getParent(), JavaElementLabels.ALL_DEFAULT), JavaElementLabels.getElementLabel(input, JavaElementLabels.ALL_DEFAULT) };
		return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_methodhierarchy_label, args);
	} else if (input != null) {
		String arg= JavaElementLabels.getElementLabel(input, JavaElementLabels.DEFAULT_QUALIFIED);
		return Messages.format(TypeHierarchyMessages.HierarchyInformationControl_hierarchy_label, arg);
	} else {
		return ""; //$NON-NLS-1$
	}
}
 
Example #28
Source File: JavaModelSearch.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the parameter type name is a generic type parameter of
 * either the specified method or its containing type.
 */
private static boolean isTypeParameter(IMethod method,
    String simpleParamTypeName) throws JavaModelException {
  List<ITypeParameter> typeParams = new ArrayList<ITypeParameter>();
  typeParams.addAll(Arrays.asList(method.getTypeParameters()));
  typeParams.addAll(Arrays.asList(method.getDeclaringType().getTypeParameters()));

  for (ITypeParameter typeParam : typeParams) {
    if (typeParam.getElementName().equals(simpleParamTypeName)) {
      return true;
    }
  }

  return false;
}
 
Example #29
Source File: DialogFactoryHelperImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
private Collection<IJavaElement> filterOutExcludedElements(IJavaElement[] src, Set<IMethod> excludedElements) {

        if (excludedElements == null || excludedElements.size() == 0) {
            return Arrays.asList(src);
        }

        Collection<IJavaElement> result = new ArrayList<>();
        for (int i = 0, size = src.length; i < size; i++) {
            if (!excludedElements.contains(src[i])) {
                result.add(src[i]);
            }
        }

        return result;
    }
 
Example #30
Source File: PatchFixesHider.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static IMethod[] removeGeneratedMethods(IMethod[] methods) throws Exception {
	List<IMethod> result = new ArrayList<IMethod>();
	for (IMethod m : methods) {
		if (m.getNameRange().getLength() > 0 && !m.getNameRange().equals(m.getSourceRange())) result.add(m);
	}
	return result.size() == methods.length ? methods : result.toArray(new IMethod[result.size()]);
}