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.haulmont.cuba.core.app.AbstractBeansMetadata.java

protected List<MethodInfo> getAvailableMethods(String beanName) {
    List<MethodInfo> methods = new ArrayList<>();
    try {//from w ww .  j  a v a2  s .  c  o m
        AutowireCapableBeanFactory beanFactory = AppContext.getApplicationContext()
                .getAutowireCapableBeanFactory();
        if (beanFactory instanceof CubaDefaultListableBeanFactory) {
            BeanDefinition beanDefinition = ((CubaDefaultListableBeanFactory) beanFactory)
                    .getBeanDefinition(beanName);
            if (beanDefinition.isAbstract())
                return methods;
        }

        Object bean = AppBeans.get(beanName);

        @SuppressWarnings("unchecked")
        List<Class> classes = ClassUtils.getAllInterfaces(bean.getClass());
        for (Class aClass : classes) {
            if (aClass.getName().startsWith("org.springframework."))
                continue;

            Class<?> targetClass = bean instanceof TargetClassAware ? ((TargetClassAware) bean).getTargetClass()
                    : bean.getClass();

            for (Method method : aClass.getMethods()) {
                if (isMethodAvailable(method)) {
                    Method targetClassMethod = targetClass.getMethod(method.getName(),
                            method.getParameterTypes());
                    List<MethodParameterInfo> methodParameters = getMethodParameters(targetClassMethod);
                    MethodInfo methodInfo = new MethodInfo(method.getName(), methodParameters);
                    addMethod(methods, methodInfo);
                }
            }

            if (methods.isEmpty()) {
                for (Method method : bean.getClass().getMethods()) {
                    if (!method.getDeclaringClass().equals(Object.class) && isMethodAvailable(method)) {
                        List<MethodParameterInfo> methodParameters = getMethodParameters(method);
                        MethodInfo methodInfo = new MethodInfo(method.getName(), methodParameters);
                        addMethod(methods, methodInfo);
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.debug(t.getMessage());
    }
    return methods;
}

From source file:com.glaf.core.util.ReflectUtils.java

/**
 * Returns the setter-method for the given field name or null if no setter
 * exists.// ww  w . ja  va 2 s.  co m
 */
public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) {
    String setterName = "set" + Character.toTitleCase(fieldName.charAt(0))
            + fieldName.substring(1, fieldName.length());
    try {
        // Using getMathods(), getMathod(...) expects exact parameter type
        // matching and ignores inheritance-tree.
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(setterName)) {
                Class<?>[] paramTypes = method.getParameterTypes();
                if (paramTypes != null && paramTypes.length == 1 && paramTypes[0].isAssignableFrom(fieldType)) {
                    return method;
                }
            }
        }
        return null;
    } catch (SecurityException e) {
        throw new RuntimeException(
                "Not allowed to access method " + setterName + " on class " + clazz.getCanonicalName());
    }
}

From source file:com.google.ratel.util.RatelUtils.java

public static void populateMethods(ClassData classData) {
    Class serviceClass = classData.getServiceClass();
    Map<String, MethodData> methodsMap = classData.getMethods();

    Method[] methods = serviceClass.getMethods();
    for (Method method : methods) {
        if (objectMethodNames.contains(method.getName())) {
            continue;
        }//  www.  j  a v a 2 s  .c  o m
        MethodData methodData = new MethodData();
        methodData.setMethod(method);
        populateParameterTypes(methodData);

        String methodPath = method.getName();

        Path pathAnnot = method.getAnnotation(Path.class);
        if (pathAnnot != null) {
            methodPath = pathAnnot.value().trim();
            if (methodPath.endsWith("/")) {
                methodPath = methodPath.substring(0, methodPath.length() - 1);
            }
        }
        if (!methodPath.startsWith("/")) {
            StringBuilder sb = new StringBuilder();
            sb.append("/").append(methodPath);
            methodPath = sb.toString();
        }

        methodData.setMethodPath(methodPath);
        methodData.setMethodName(method.getName());
        methodsMap.put(methodPath, methodData);
    }
}

From source file:com.haulmont.cuba.web.gui.components.table.LinkCellClickListener.java

protected Method findLinkInvokeMethod(Class cls, String methodName) {
    Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName,
            new Class[] { Entity.class, String.class });
    if (exactMethod != null) {
        return exactMethod;
    }//  w ww  .j a v  a2  s.  c om

    // search through all methods
    Method[] methods = cls.getMethods();
    for (Method availableMethod : methods) {
        if (availableMethod.getName().equals(methodName)) {
            if (availableMethod.getParameterCount() == 2 && Void.TYPE.equals(availableMethod.getReturnType())) {
                if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0])
                        && String.class == availableMethod.getParameterTypes()[1]) {
                    // get accessible version of method
                    return MethodUtils.getAccessibleMethod(availableMethod);
                }
            }
        }
    }
    return null;
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java

private Method getJNDIConnectionUtilMethod(String methodName) throws Exception {
    Class jndiConnectionUtilClass = getJNDIConnectionUtil();
    if (jndiConnectionUtilClass == null)
        return null;
    Method[] methods = jndiConnectionUtilClass.getMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            return method;
        }/*from  w w w.j  a va 2 s.  c  om*/
    }
    throw new Exception("Invalid Method: " + methodName);
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

/**
 * TODO//from   w w  w  .  j  a  va  2  s. c  om
 * 
 * @param controllerClass The <code>Controller</code> class to search methods for.
 * @return a map containing the method's name as the key and its configuration as the value.
 * 
 * @see org.apache.struts2.convention.annotation.Action
 * @see javax.ws.rs.Path
 * @see javax.ws.rs.HttpMethod
 * @see javax.ws.rs.GET
 * @see javax.ws.rs.POST
 * @see javax.ws.rs.PUT
 * @see javax.ws.rs.DELETE
 * @see javax.ws.rs.Consumes
 * @see javax.ws.rs.Produces
 */
protected Map<String, ActionMethodConfigBean> findActionMethods(Class<?> controllerClass) {
    Map<String, ActionMethodConfigBean> map = new HashMap<String, ActionMethodConfigBean>();
    Method[] methods = controllerClass.getMethods();
    for (Method method : methods) {

        // first of all, lets validate the candidate...
        Class<?> returnType = method.getReturnType();
        if (returnType == null
                || (!returnType.equals(String.class) && !returnType.isAssignableFrom(Response.class))
                || method.getParameterTypes().length > 0 || Modifier.isStatic(method.getModifiers())) {
            continue;
        }

        ActionMethodConfigBean methodConfig = new ActionMethodConfigBean();
        methodConfig.setName(method.getName());

        // Guessing http method
        String httpMethod = this.guessHttpMethod(method).value();
        methodConfig.setHttpMethod(httpMethod);

        // if a @Action annotation is found then keep it for results, interceptors and so to be configured properly
        final Action actionAnnotation = ReflectionUtils.getAnnotation(Action.class, method);
        if (actionAnnotation != null) {
            methodConfig.setAction(actionAnnotation);
            methodConfig.setUriTemplate(actionAnnotation.value().trim());
        }

        // if a @Path annotation is found then its value overwrites the @Action one (if found too)
        final Path pathAnnotation = ReflectionUtils.getAnnotation(Path.class, method);
        if (pathAnnotation != null) {
            methodConfig.setUriTemplate(pathAnnotation.value().trim());
        }

        // are there any restrinctions for response type
        //         methodConfig.setProduces(method.getAnnotation(Produces.class));
        // TODO @Consumes

        // if no URI template found, then guess based on method's name
        if (StringUtils.isBlank(methodConfig.getUriTemplate())) {
            // TODO filter methods
            //methodConfig.setUriTemplate(actionNameBuilder.build(method.getName()));
        } else {
            map.put(method.getName(), methodConfig);
        }

        //         map.put(method.getName(), methodConfig); TODO remove 'else' above after impl method filtering
    }
    return map;
}

From source file:com.quancheng.saluki.core.config.RpcReferenceConfig.java

private void addMethods(Map<String, String> params) {
    Set<String> retryMethods = getRetryMethods();
    Boolean isNotGeneric = !isGeneric();
    Boolean isNotStub = !isGrpcStub();
    if (isNotGeneric && isNotStub && CollectionUtils.isNotEmpty(retryMethods)) {
        try {//ww w  . j  a  v a  2s  .  c om
            String serviceName = getServiceName();
            Class<?> serviceClzz = ReflectUtils.name2class(serviceName);
            setServiceClass(serviceClzz);
            for (String methodName : retryMethods) {
                Method hasMethod = null;
                for (Method method : serviceClzz.getMethods()) {
                    if (method.getName().equals(methodName)) {
                        hasMethod = method;
                    }
                }
                if (hasMethod == null) {
                    throw new IllegalArgumentException(
                            "The interface " + serviceName + " not found method " + methodName);
                }
            }
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    }
    params.put(Constants.METHODS_KEY, StringUtils.join(retryMethods, ","));
}

From source file:com.jayway.jaxrs.hateoas.DefaultHateoasContext.java

private void mapClass(Class<?> clazz, String path) {

    if (!isInitialized(clazz)) {
        logger.info("Mapping class {}", clazz);

        if (path.endsWith("/")) {
            path = StringUtils.removeEnd(path, "/");
        }/*from  w w w  .jav  a2s.c o  m*/

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (!method.getDeclaringClass().equals(Object.class)) {
                mapMethod(clazz, path, method);
            }
        }
    } else {
        logger.info("Class {} already mapped. Skipped mapping.", clazz);
    }
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java

private List<EntityPropertySetter> createEntityPropertySetters(ParameterConverterService converterService,
        Class type, StoredProcedureInfo procedureInfo, String tablePrefix) {
    List<EntityPropertySetter> list = new LinkedList<EntityPropertySetter>();
    for (Method getterMethod : type.getMethods()) {
        Column columnAnnotation = getterMethod.getAnnotation(Column.class);
        if (columnAnnotation != null) {
            Method setterMethod = BlockFactoryUtils.findSetterMethod(type, getterMethod);
            String columnName = tablePrefix + columnAnnotation.name();
            if (LOG.isDebugEnabled()) {
                LOG.debug("         Mapping result set for {}.{}() to {} ...",
                        new String[] { type.getSimpleName(), getterMethod.getName(), columnName });
            }/*from w ww .  jav  a  2s . c  o m*/
            ResultSetColumnInfo resultSetColumnInfo = procedureInfo.getResultSetColumn(columnName);
            if (resultSetColumnInfo == null) {
                throw new IllegalStateException(String.format(
                        "For method %s.%s() column '%s' was not found in result set for procedure %s() ",
                        type.getSimpleName(), getterMethod.getName(), columnName,
                        procedureInfo.getProcedureName()));
            }
            try {
                IParameterConverter paramConverter = converterService
                        .getConverter(resultSetColumnInfo.getDataType(), getterMethod.getReturnType());
                list.add(new EntityPropertySetter(setterMethod, paramConverter,
                        resultSetColumnInfo.getColumnName(), null, resultSetColumnInfo.getDataType()));
            } catch (IllegalStateException e) {
                throw new IllegalStateException(String.format(
                        "Converter was not found for method %s.%s() [ column '%s' in procedure %s()]",
                        type.getSimpleName(), getterMethod.getName(), columnName,
                        procedureInfo.getProcedureName()), e);
            }
        }
    }
    return list;
}

From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java

private void addDataConverterObject(String className) {
    Class<?> cls;
    try {//from   ww  w . ja va 2s.c o m
        cls = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("No such class: " + className);
    }
    StringBuilder excludes = new StringBuilder();
    for (Method m : cls.getMethods()) {
        if (logger.isDebugEnabled()) {
            logger.debug("CHECKING " + cls.getSimpleName() + "." + m.getName() + "("
                    + m.getParameterTypes().length + ") -> " + Arrays.asList(m.getAnnotations()));
        }
        if (!m.isAnnotationPresent(RemoteProperty.class)) {
            if (logger.isDebugEnabled()) {
                logger.debug("EXCLUDING " + cls.getSimpleName() + "." + m.getName() + " -> "
                        + Arrays.asList(m.getAnnotations()));
            }
            excludes.append(propName(m)).append(',');
        }
    }
    BeanConverter beanConverter = new BeanConverter();
    beanConverter.setInstanceType(cls);
    beanConverter.setExclude(excludes.toString());
    ConverterManager cm = this.getBean(ConverterManager.class);
    cm.addConverter(cls.getName(), beanConverter);
    if (logger.isDebugEnabled()) {
        logger.debug("CONVERTER: " + cls.getName() + " -> " + excludes);
    }
}