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

The following examples show how to use org.eclipse.jdt.core.IType#getMethods() . 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: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test4() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test4.java");
	IType testClass = cu.createType("public class Test4 implements B, E {\n}\n", null, true, null);

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

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "e", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Hashtable", "java.util.NoSuchElementException" }, imports);
}
 
Example 2
Source File: JavaElementDelegateMainLaunch.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected boolean containsElementsSearchedFor(IFile file) {
	IJavaElement element = JavaCore.create(file);
	if (element == null || !element.exists() || ! (element instanceof ICompilationUnit)) {
		return false;
	}
	try {
		ICompilationUnit cu = (ICompilationUnit) element;
		for (IType type : cu.getAllTypes()) {
			for (IMethod method : type.getMethods()) {
				int flags = method.getFlags();
				if (Modifier.isPublic(flags) && Modifier.isStatic(flags) && "main".equals(method.getElementName())
						&& method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals("[QString;")) { //$NON-NLS-1$
					return true;
				}
			}
		}
	} catch (JavaModelException e) {
		log.error(e.getMessage(), e);
	}
	return super.containsElementsSearchedFor(file);
}
 
Example 3
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test3() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test3.java");
	IType testClass = cu.createType("public class Test3 extends D {\n}\n", null, true, null);

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

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "d", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Hashtable", "java.util.Enumeration" }, imports);
}
 
Example 4
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test2() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test2.java");
	IType testClass = cu.createType("public class Test2 extends C implements B {\n}\n", null, true, null);

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

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "c", "d", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Enumeration", "java.util.Hashtable" }, imports);
}
 
Example 5
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test1() throws Exception {
	ICompilationUnit cu = fPackageP.getCompilationUnit("Test1.java");
	IType testClass = cu.createType("public class Test1 extends A implements B {\n}\n", null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "a()", "b(Vector<Date>)", "c(Hashtable)" }, overridableMethods);

	addAndApplyOverridableMethods(testClass, overridableMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "a", "b", "c", "equals", "clone", "toString", "finalize", "hashCode" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[] { "java.util.Date", "java.util.Hashtable", "java.util.Vector" }, imports);
}
 
Example 6
Source File: GroovyDocumentUtil.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
public static void refreshUserLibrary(Repository repository) {
    try {
        FunctionsRepositoryFactory.getUserFunctionCatgory().removeAllFunctions();
        GroovyRepositoryStore store = repository.getRepositoryStore(GroovyRepositoryStore.class);
        IJavaProject javaProject = repository.getJavaProject();
        for (IRepositoryFileStore artifact : store.getChildren()) {
            IType type = javaProject.findType(artifact.getDisplayName().replace("/", "."));
            if (type != null) {
                for (IMethod m : type.getMethods()) {
                    if (m.getFlags() == (Flags.AccStatic | Flags.AccPublic)) {
                        FunctionsRepositoryFactory.getUserFunctionCatgory()
                                .addFunction(new GroovyFunction(m, FunctionsRepositoryFactory.getUserFunctionCatgory()));
                    }
                }
            }
        }
    } catch (Exception e) {
        GroovyPlugin.logError(e);
    }
}
 
Example 7
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String getUniqueMethodName(ASTNode astNode, String suggestedName) throws JavaModelException {
	while (astNode != null && !(astNode instanceof TypeDeclaration || astNode instanceof AnonymousClassDeclaration)) {
		astNode = astNode.getParent();
	}
	if (astNode instanceof TypeDeclaration) {
		ITypeBinding typeBinding = ((TypeDeclaration) astNode).resolveBinding();
		if (typeBinding == null) {
			return suggestedName;
		}
		IType type = (IType) typeBinding.getJavaElement();
		if (type == null) {
			return suggestedName;
		}
		IMethod[] methods = type.getMethods();

		int suggestedPostfix = 2;
		String resultName = suggestedName;
		while (suggestedPostfix < 1000) {
			if (!hasMethod(methods, resultName)) {
				return resultName;
			}
			resultName = suggestedName + suggestedPostfix++;
		}
	}
	return suggestedName;
}
 
Example 8
Source File: JavaModelSearch.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static IMethod findMethodOrCtor(IType type, String methodName,
    String[] paramTypes, boolean isConstructor) {
  try {
    IMethod[] methods = type.getMethods();
    for (IMethod method : methods) {
      if (methodSignaturesEqual(type, methodName, paramTypes, isConstructor,
          method)) {
        return method;
      }
    }
  } catch (JavaModelException e) {
    CorePluginLog.logError(e);
  }

  return null;
}
 
Example 9
Source File: MethodOverrideTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds an overridden method in a type. With generics it is possible that 2 methods in the same type are overridden at the same time.
 * In that case the first overridden method found is returned.
 * @param overriddenType The type to find methods in
 * @param overriding The overriding method
 * @return The first overridden method or <code>null</code> if no method is overridden
 * @throws JavaModelException if a problem occurs
 */
public IMethod findOverriddenMethodInType(IType overriddenType, IMethod overriding) throws JavaModelException {
	int flags= overriding.getFlags();
	if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor())
		return null;
	IMethod[] overriddenMethods= overriddenType.getMethods();
	for (int i= 0; i < overriddenMethods.length; i++) {
		IMethod overridden= overriddenMethods[i];
		flags= overridden.getFlags();
		if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overridden.isConstructor())
			continue;
		if (isSubsignature(overriding, overridden)) {
			return overridden;
		}
	}
	return null;
}
 
Example 10
Source File: JavaElementUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static IMethod[] getAllConstructors(IType type) throws JavaModelException {
	if (JavaModelUtil.isInterfaceOrAnnotation(type)) {
		return new IMethod[0];
	}
	List<IMethod> result= new ArrayList<>();
	IMethod[] methods= type.getMethods();
	for (int i= 0; i < methods.length; i++) {
		IMethod iMethod= methods[i];
		if (iMethod.isConstructor()) {
			result.add(iMethod);
		}
	}
	return result.toArray(new IMethod[result.size()]);
}
 
Example 11
Source File: OverrideMethodsTestCase.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug297183() throws Exception {
	StringBuilder buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("interface Shape {\r\n");
	buf.append("  int getX();\r\n");
	buf.append("  int getY();\r\n");
	buf.append("  int getEdges();\r\n");
	buf.append("  int getArea();\r\n");
	buf.append("}\r\n");
	fPackageP.createCompilationUnit("Shape.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package p;\n");
	buf.append("interface Circle extends Shape {\r\n");
	buf.append("  int getR();\r\n");
	buf.append("}\r\n");
	buf.append("\r\n");
	fPackageP.createCompilationUnit("Circle.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package P;\n");
	buf.append("public class DefaultCircle implements Circle {\n");
	buf.append("}\n");
	ICompilationUnit cu = fPackageP.getCompilationUnit("DefaultCircle.java");
	IType testClass = cu.createType(buf.toString(), null, true, null);

	List<OverridableMethod> overridableMethods = getOverridableMethods(testClass);
	checkUnimplementedMethods(new String[] { "getX()", "getY()", "getEdges()", "getArea()", "getR()" }, overridableMethods);
	List<OverridableMethod> unimplementedMethods = overridableMethods.stream().filter((method) -> method.unimplemented).collect(Collectors.toList());
	addAndApplyOverridableMethods(testClass, unimplementedMethods);

	IMethod[] methods = testClass.getMethods();
	checkMethods(new String[] { "getX", "getY", "getEdges", "getArea", "getR" }, methods);

	IImportDeclaration[] imports = cu.getImports();
	checkImports(new String[0], imports);
}
 
Example 12
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 13
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds a method for the given <code>IMethodBinding</code>. Returns
 * <code>null</code> if the type doesn't contain a corresponding method.
 * @param method the method to find
 * @param type the type to look in
 * @return the corresponding IMethod or <code>null</code>
 * @throws JavaModelException if an error occurs in the Java model
 * @deprecated Use {@link #findMethodInHierarchy(ITypeBinding, String, String[])} or {@link JavaModelUtil}
 */
public static IMethod findMethod(IMethodBinding method, IType type) throws JavaModelException {
	method= method.getMethodDeclaration();

	IMethod[] candidates= type.getMethods();
	for (int i= 0; i < candidates.length; i++) {
		IMethod candidate= candidates[i];
		if (candidate.getElementName().equals(method.getName()) && sameParameters(method, candidate)) {
			return candidate;
		}
	}
	return null;
}
 
Example 14
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Does <code>type</code> contain a method with <code>name</code>?
 *
 * @param type the type to inspect
 * @param name the name of the method to search for
 * @return true if has such a method
 * @throws JavaModelException if methods could not be retrieved
 * @since 3.4
 */
private boolean hasMethod(IType type, String name) throws JavaModelException {
	IMethod[] methods= type.getMethods();
	for (int i= 0; i < methods.length; i++) {
		if (name.equals(methods[i].getElementName()))
			return true;
	}

	return false;
}
 
Example 15
Source File: MethodDeclarationCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set<String> suggestedMethods, Collection<IJavaCompletionProposal> result) throws CoreException {
	IMethod[] methods= type.getMethods();
	if (!type.isInterface()) {
		String constructorName= type.getElementName();
		if (constructorName.length() > 0 && constructorName.startsWith(prefix) && !hasMethod(methods, constructorName) && suggestedMethods.add(constructorName)) {
			result.add(new MethodDeclarationCompletionProposal(type, constructorName, null, offset, length, relevance + 500));
		}
	}

	if (prefix.length() > 0 && !"main".equals(prefix) && !hasMethod(methods, prefix) && suggestedMethods.add(prefix)) { //$NON-NLS-1$
		if (!JavaConventionsUtil.validateMethodName(prefix, type).matches(IStatus.ERROR))
			result.add(new MethodDeclarationCompletionProposal(type, prefix, Signature.SIG_VOID, offset, length, relevance));
	}
}
 
Example 16
Source File: GetterSetterCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set<String> suggestedMethods, Collection<IJavaCompletionProposal> result) throws CoreException {
	if (prefix.length() == 0) {
		relevance--;
	}

	IField[] fields= type.getFields();
	IMethod[] methods= type.getMethods();
	for (int i= 0; i < fields.length; i++) {
		IField curr= fields[i];
		if (!JdtFlags.isEnum(curr)) {
			String getterName= GetterSetterUtil.getGetterName(curr, null);
			if (Strings.startsWithIgnoreCase(getterName, prefix) && !hasMethod(methods, getterName)) {
				suggestedMethods.add(getterName);
				int getterRelevance= relevance;
				if (JdtFlags.isStatic(curr) && JdtFlags.isFinal(curr))
					getterRelevance= relevance - 1;
				result.add(new GetterSetterCompletionProposal(curr, offset, length, true, getterRelevance));
			}

			if (!JdtFlags.isFinal(curr)) {
				String setterName= GetterSetterUtil.getSetterName(curr, null);
				if (Strings.startsWithIgnoreCase(setterName, prefix) && !hasMethod(methods, setterName)) {
					suggestedMethods.add(setterName);
					result.add(new GetterSetterCompletionProposal(curr, offset, length, false, relevance));
				}
			}
		}
	}
}
 
Example 17
Source File: JavaModelSearch.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the first constructor in the specified type.
 */
public static IJavaElement findFirstCtor(IType type) {
  try {
    for (IMethod method : type.getMethods()) {
      if (method.isConstructor()) {
        return method;
      }
    }
  } catch (JavaModelException e) {
    CorePluginLog.logError(e);
  }
  return null;
}
 
Example 18
Source File: JDTMethodHelper.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public static List<IMethod> allPublicMethodWithoutParameterReturningNonVoid(final IType type)
        throws JavaModelException {
    List<IMethod> methods = new ArrayList<>();
    if (isGroovySourceType(type)) {
        methods.addAll(listPropertyGetterMethods(type));
    }
    for (final IMethod method : type.getMethods()) {
        if (isValidGetterMethod(methods, method)) {
            methods.add(method);
        }
    }
    ITypeHierarchy typeHierarchy = type.newSupertypeHierarchy(Repository.NULL_PROGRESS_MONITOR);
    if (typeHierarchy != null) {
        Stream.of(typeHierarchy.getAllSuperclasses(type))
                .filter(t -> !Object.class.getName().equals(t.getElementName()))
                .flatMap(t -> {
                    try {
                        return Stream.of(t.getMethods());
                    } catch (JavaModelException e) {
                        return Stream.empty();
                    }
                })
                .filter(m -> isValidGetterMethod(methods, m))
                .forEach(methods::add);
    }
    return methods;
}
 
Example 19
Source File: ResolveMainMethodHandler.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the main method defined in the type.
 */
public static IMethod getMainMethod(IType type) throws JavaModelException {
    for (IMethod method : type.getMethods()) {
        // Have at most one main method in the member methods of the type.
        if (method.isMainMethod()) {
            return method;
        }
    }

    return null;
}
 
Example 20
Source File: MethodProposalInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Finds a method by name. This searches for a method with a name and
 * signature. Parameter types are only compared by the simple name, no
 * resolving for the fully qualified type name is done. Constructors are
 * only compared by parameters, not the name.
 *
 * @param name The name of the method to find
 * @param paramTypes The type signatures of the parameters e.g.
 *        <code>{"QString;","I"}</code>
 * @param isConstructor If the method is a constructor
 * @param type the given type in which to search for methods
 * @param typeVariables a map from type variables to concretely used types
 * @return The found method or <code>null</code>, if nothing found
 * @throws JavaModelException if the method does not exist or if an exception occurs while accessing its corresponding resource
 */
private IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type, Map<String, char[]> typeVariables) throws JavaModelException {
	IMethod[] methods = type.getMethods();
	for (int i= methods.length - 1; i >= 0; i--) {
		if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i], typeVariables, type)) {
			return methods[i];
		}
	}
	return fFallbackMatch;
}