Example usage for java.lang Class getMethods

List of usage examples for java.lang Class getMethods

Introduction

In this page you can find the example usage for java.lang Class getMethods.

Prototype

@CallerSensitive
public Method[] getMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Usage

From source file:com.liferay.portal.remote.json.web.service.extender.internal.ServiceJSONWebServiceScannerStrategy.java

@Override
public MethodDescriptor[] scan(Object service) {
    Class<?> clazz = null;

    try {/*w w w. j a  v a 2  s.com*/
        clazz = getTargetClass(service);
    } catch (Exception e) {
        return new MethodDescriptor[0];
    }

    Method[] methods = clazz.getMethods();

    List<MethodDescriptor> methodDescriptors = new ArrayList<>(methods.length);

    for (Method method : methods) {
        Class<?> declaringClass = method.getDeclaringClass();

        if (declaringClass != clazz) {
            continue;
        }

        methodDescriptors.add(new MethodDescriptor(method));
    }

    return methodDescriptors.toArray(new MethodDescriptor[methodDescriptors.size()]);
}

From source file:com.amalto.core.metadata.ClassRepository.java

private static Method[] getMethods(Class clazz) {
    // TMDM-5851: Work around several issues in introspection (getDeclaredMethods() and getMethods() may return
    // inherited methods if returned type is a sub class of super class method).
    Map<String, Class<?>> superClassMethods = new HashMap<String, Class<?>>();
    if (clazz.getSuperclass() != null) {
        for (Method method : clazz.getSuperclass().getMethods()) {
            superClassMethods.put(method.getName(), method.getReturnType());
        }//from   www .ja v  a 2  s .  c o  m
    }
    Map<String, Method> methods = new HashMap<String, Method>();
    for (Method method : clazz.getDeclaredMethods()) {
        if (!(superClassMethods.containsKey(method.getName())
                && superClassMethods.get(method.getName()).equals(method.getReturnType()))) {
            methods.put(method.getName(), method);
        }
    }
    Method[] allMethods = clazz.getMethods();
    for (Method method : allMethods) {
        if (!methods.containsKey(method.getName())) {
            methods.put(method.getName(), method);
        }
    }
    Method[] classMethods = methods.values().toArray(new Method[methods.size()]);
    // TMDM-5483: getMethods() does not always return methods in same order: sort them to ensure fixed order.
    Arrays.sort(classMethods, new Comparator<Method>() {
        @Override
        public int compare(Method method1, Method method2) {
            return method1.getName().compareTo(method2.getName());
        }
    });
    return classMethods;
}

From source file:com.tacitknowledge.noexcuses.MethodTester.java

/**
 * Pruning {@link Object} defined methods from the list of 
 * the provided <code>testClass</code> methods. This way we're
 * assuring that we end up with the list of methods that are pertinent
 * to at least one level beyond that of <code>Object</code> class.
 * //from w w  w  .ja v a2s  . c  o m
 * @param testClass {@link Class} whose methods to prune
 * @return collection of {@link Method}s that contain all of the <code>testClass</code>
 *  defined methods with the exclusion of those defined on {@link Object} level.
 */
private Collection<Method> pruneMethods(Class<?> testClass) {
    Method[] methods = testClass.getMethods();
    Method[] objMethods = Object.class.getMethods();
    Collection<Method> results = new ArrayList<Method>(Arrays.asList(methods));
    results.removeAll(new ArrayList<Method>(Arrays.asList(objMethods)));
    return results;
}

From source file:org.openamf.invoker.SpringBeanInvoker.java

private RankedMethod getServiceMethod(Class serviceClass, String methodName, List parameters)
        throws SecurityException, NoSuchMethodException {

    RankedMethod serviceMethod = null;/*  w  ww . java  2s .co  m*/
    Method[] methods = serviceClass.getMethods();
    List rankedMethods = new ArrayList(methods.length);
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        RankedMethod rankedMethod = new RankedMethod(method, methodName, parameters);
        if (rankedMethod.isInvokable()) {
            rankedMethods.add(rankedMethod);
        }
    }
    if (rankedMethods.size() > 0) {
        Collections.sort(rankedMethods);
        RankedMethod topRankedMethod = (RankedMethod) rankedMethods.get(0);
        serviceMethod = topRankedMethod;
    }
    if (serviceMethod == null) {
        String errorDesc = serviceClass + "." + methodName + "(" + parameters + ")";
        throw new NoSuchMethodException(errorDesc);
    }
    return serviceMethod;
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

private <T> void checkMethodOwnFunctionConfiguration(Class<T> interfaceType, final Object configuration)
        throws InitializationException {
    Method[] methods = interfaceType.getMethods();
    for (Method method : methods) {
        if (IGNORED_SET.contains(method.getName())) {
            continue;
        }//  ww  w .  j  a v  a 2  s.  co m
        if (method.getAnnotation(Deprecated.class) != null) {
            continue;
        }
        try {
            Class<?> c = PropertyUtils.getPropertyType(configuration, method.getName());
            Preconditions.checkArgument(c == FunctionConfiguration.class);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException
                | IllegalArgumentException e) {
            throw new InitializationException(
                    "FunctionConfiguration for '" + method.getName() + "' cannot be found");
        }
    }

}

From source file:com.evanzeimet.queryinfo.jpa.attribute.DefaultEntityAnnotationsAttributeInfoResolver.java

protected List<Method> findAnnotatedMethods(Class<T> entityClass, Class<? extends Annotation> annotationClass) {
    Method[] methods = entityClass.getMethods();

    int methodCount = methods.length;
    List<Method> annotatedMethods = new ArrayList<Method>(methodCount);

    for (Method method : methods) {
        if (method.isAnnotationPresent(annotationClass)) {
            annotatedMethods.add(method);
        }/*  www .  j  a va 2  s.co  m*/
    }

    return annotatedMethods;
}

From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java

/**
 * Parse all controllers using the {@link DocumentedController} annotation.
 * //from w ww. ja v  a 2  s  .c om
 * @param resourcesFolder
 * @return
 * @throws SiteWhereException
 */
protected static List<ParsedController> parseControllers(File resourcesFolder) throws SiteWhereException {
    Reflections reflections = new Reflections("com.sitewhere.web.rest.controllers");
    Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(DocumentedController.class);
    List<ParsedController> results = new ArrayList<ParsedController>();
    for (Class<?> controller : controllers) {
        results.add(parseController(controller, resourcesFolder));
    }
    Collections.sort(results, new Comparator<ParsedController>() {

        @Override
        public int compare(ParsedController o1, ParsedController o2) {
            if (o1.isGlobal() && !o2.isGlobal()) {
                return -1;
            } else if (!o1.isGlobal() && o2.isGlobal()) {
                return 1;
            }
            return o1.getName().compareTo(o2.getName());
        }
    });
    int methodCount = 0;
    for (ParsedController controller : results) {
        methodCount += controller.getMethods().size();
    }
    System.out.println(
            "Found " + controllers.size() + " documented controllers containing " + methodCount + " methods.");
    return results;
}

From source file:mitm.common.hibernate.AutoCommitProxyFactory.java

private void findInjectMethods(Class<T> clazz) throws NoSuchMethodException {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
        if (method.isAnnotationPresent(InjectHibernateSession.class)) {
            String parameterDescriptor = RuntimeSupport.makeDescriptor(method);

            if (!parameterDescriptor.equals("(Lorg/hibernate/Session;)V")) {
                throw new NoSuchMethodException(
                        "@InjectHibernateSession method does not have the correct parameters.");
            }// w w  w.  j  a  v  a  2s.  c om

            injectHibernateSessionMethod = method;
        } else if (method.isAnnotationPresent(InjectHibernateSessionSource.class)) {
            String parameterDescriptor = RuntimeSupport.makeDescriptor(method);

            if (!parameterDescriptor.equals("(Lmitm/common/hibernate/HibernateSessionSource;)V")) {
                throw new NoSuchMethodException(
                        "@InjectHibernateSessionSource method does not have the correct parameters.");
            }

            injectHibernateSessionSourceMethod = method;
        }
    }
}

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.MemberLookupResolver.java

/**
 * Fallback used to load the methods from classloader
 *
 * @param clazzname//from  www.  j av a 2  s .  c o m
 * @param variable
 * @return set with all methods, can be empty
 */
private Set<MemberLookupResult> getMethodsFromClassLoader(String clazzname, String variable) {
    final Set<MemberLookupResult> ret = new LinkedHashSet<>();
    try {
        Class clazz = classPath.getClassLoader(true).loadClass(clazzname);
        for (Method method : clazz.getMethods()) {
            if (method.getReturnType() != Void.TYPE && GETTER_PATTERN.matcher(method.getName()).matches()) {
                ret.add(new MemberLookupResult(variable, method.getName(), method.getReturnType().getName()));
            }
        }
        for (Field field : clazz.getFields()) {
            ret.add(new MemberLookupResult(variable, field.getName(), field.getType().getName()));
        }
    } catch (ClassNotFoundException cnfe) {
        LOGGER.log(Level.FINE, "Could not resolve class " + clazzname + "defined for variable " + variable,
                cnfe);
    }
    return ret;
}

From source file:com.wordnik.swagger.testframework.JavaTestCaseExecutor.java

private void executeTestCase(String resourceName, String servicePackageName, String suggestedName,
        Map<String, String> queryAndPathParameters, String postData) {

    String className = namingPolicyProvider.getServiceName(resourceName);
    String methodName = suggestedName;
    //3/*from w w w  .  j  a  va 2 s  .c o  m*/
    try {
        Class apiClass = Class.forName(servicePackageName + "." + className);
        Method[] methods = apiClass.getMethods();
        Method methodToExecute = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                methodToExecute = method;
                break;
            }
        }

        if (methodToExecute != null) {
            //4
            Object[] arguments = populateArgumentsForTestCaseExecution(methodToExecute, queryAndPathParameters,
                    postData, className, resourceName);
            Object output = null;
            if (arguments != null && arguments.length > 0) {
                //5
                output = methodToExecute.invoke(null, arguments);
            } else {
                //5
                output = methodToExecute.invoke(null);
            }
            //6
            System.out.println("SUCCESS");
            System.out.println(APITestRunner.convertObjectToJSONString(output));

        }
    } catch (APIException e) {
        StringWriter sWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(sWriter);
        e.printStackTrace(writer);
        System.out.println(sWriter.getBuffer().toString());
        System.out.println(e.getMessage());
        System.out.println("ERROR");
        try {
            System.out.println(APITestRunner.convertObjectToJSONString(e));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } catch (Exception e) {
        StringWriter sWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(sWriter);
        e.printStackTrace(writer);
        System.out.println(sWriter.getBuffer().toString());
        e.printStackTrace();
        System.out.println("ERROR");
        try {
            APIException apiException = new APIException(APIExceptionCodes.SYSTEM_EXCEPTION, e.getMessage());
            System.out.println(APITestRunner.convertObjectToJSONString(apiException));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}