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.phoenixnap.oss.ramlapisync.parser.ResourceParser.java

/**
 * Loads the relevant methods from a service and extracts the information relevant to raml. Methods from the Object
 * class are ignored/*  w w w  .  j  av  a2  s .co  m*/
 * 
 * @param clazz
 * @return
 */
private List<Resource> getMethodsFromService(Class<?> clazz, JavaDocStore javaDoc, Resource parentResource) {
    List<Resource> resources = new ArrayList<>();
    try {
        for (Method method : clazz.getMethods()) {
            if (!IGNORE_METHOD_REGEX.matcher(method.getName()).matches() && shouldAddMethodToApi(method)) {
                extractAndAppendResourceInfo(method, javaDoc.getJavaDoc(method), parentResource);
            }
        }
    } catch (NoClassDefFoundError nEx) {
        logger.error("Unable to get methods - skipping class " + clazz, nEx);
    }
    return resources;
}

From source file:be.fgov.kszbcss.rhq.websphere.mbean.MBeanClient.java

public <T> T getProxy(Class<T> iface) {
    synchronized (proxies) {
        Object proxy = proxies.get(iface);
        if (proxy == null) {
            if (log.isDebugEnabled()) {
                log.debug("Creating dynamic proxy for MBean " + locator);
            }/*from  w w w  .  j  a v  a 2s  .  c  om*/
            for (Method method : iface.getMethods()) {
                if (!throwsException(method, JMException.class)
                        || !throwsException(method, ConnectorException.class)) {
                    throw new IllegalArgumentException(iface.getName() + " is not a valid proxy class: method "
                            + method.getName() + " must declare JMException and ConnectorException");
                }
            }
            proxy = Proxy.newProxyInstance(MBeanClient.class.getClassLoader(),
                    new Class<?>[] { iface, MBeanClientProxy.class }, new MBeanClientInvocationHandler(this));
            proxies.put(iface, proxy);
        }
        return iface.cast(proxy);
    }
}

From source file:com.tyro.oss.pact.spring4.pact.provider.PactTestRunner.java

private Map<String, Method> getProviderStateMethods(Class<?> clazz) {
    Map<String, Method> providerStateMethods = new HashMap<>();

    for (Method method : clazz.getMethods()) {
        ProviderState annotation = AnnotationUtils.findAnnotation(method, ProviderState.class);
        if (annotation != null) {
            String state = annotation.value();
            if (StringUtils.isEmpty(state)) {
                state = method.getName();
            }//  w w  w  . j  ava 2s  .  c  o  m
            if (providerStateMethods.containsKey(state)) {
                throw new IllegalStateException("There must be only one setup method per provider state");
            }
            providerStateMethods.put(state, method);
        }
    }

    return providerStateMethods;
}

From source file:gov.nih.nci.system.web.struts.action.UpdateAction.java

private void setParameterValue(Class klass, Object instance, String name, String value) throws Exception {
    if (value != null && value.trim().length() == 0)
        return;/*  ww  w.  j a va 2  s  . c o m*/

    String paramName = name.substring(0, 1).toUpperCase() + name.substring(1);
    Method[] allMethods = klass.getMethods();
    for (Method m : allMethods) {
        String mname = m.getName();
        if (mname.equals("get" + paramName)) {
            Class type = m.getReturnType();
            Class[] argTypes = new Class[] { type };

            Method method = null;
            while (klass != Object.class) {
                try {
                    Method setMethod = klass.getDeclaredMethod("set" + paramName, argTypes);
                    setMethod.setAccessible(true);
                    setMethod.invoke(instance, convertValue(type, value));
                    break;
                } catch (NoSuchMethodException ex) {
                    klass = klass.getSuperclass();
                }
            }
        }
    }
}

From source file:com.opengamma.language.external.ExternalFunctionHandler.java

/**
 * Creates a handler wrapper for a given class.
 * /*from  ww  w  . j a v  a  2s .  c  o  m*/
 * @param clazz the class containing external function methods
 */
public ExternalFunctionHandler(final Class<?> clazz) {
    final Constructor<?>[] constructors = clazz.getConstructors();
    final Method[] methods = clazz.getMethods();
    final ArrayList<PublishedFunction> functions = new ArrayList<PublishedFunction>(
            constructors.length + methods.length);
    // Only need an instance of the class if one or more annotated methods are not static. In this case, the same
    // instance will be re-used for each non-static method. If instantiation fails (e.g. no default constructor), just
    // skip instance methods and log warnings.
    Object sharedInstance = null;
    boolean instantiateFailed = false;
    for (Constructor<?> constructor : constructors) {
        if (!constructor.isAnnotationPresent(ExternalFunction.class)) {
            continue;
        }
        s_logger.debug("Found constructor {}", constructor);
        // If there is a constructor method, can only have static declarations
        instantiateFailed = true;
        functions.add(new ConstructorWrapper(constructor));
    }
    for (Method method : methods) {
        if (!method.isAnnotationPresent(ExternalFunction.class)) {
            continue;
        }
        s_logger.debug("Found method {}", method);
        final Object instance;
        if (Modifier.isStatic(method.getModifiers())) {
            instance = null;
        } else {
            if (instantiateFailed) {
                s_logger.warn("Skipping method {}", method);
                continue;
            } else if (sharedInstance == null) {
                sharedInstance = tryGetInstance(clazz);
                if (sharedInstance == null) {
                    s_logger.warn("Default instantiation failed for {}", clazz);
                    s_logger.warn("Skipping method {}", method);
                    instantiateFailed = true;
                    continue;
                }
            }
            instance = sharedInstance;
        }
        functions.add(new MethodWrapper(method, instance));
    }
    functions.trimToSize();
    _functions = functions;
}

From source file:com.toolsverse.mvc.pojo.PojoWrapper.java

/**
 * Instantiate an obejct of the type P. Intersepts getters, setters, readres and writers. 
 *
 * @param pojoClass the pojo class/*from  www .ja  v  a 2  s .  c  om*/
 */
@SuppressWarnings("unchecked")
private void init(Class<?> pojoClass) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(pojoClass);
    enhancer.setCallback(this);
    _pojo = (P) enhancer.create();

    Method[] methods = pojoClass.getMethods();

    for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        if (annotations != null)
            for (Annotation annotation : annotations) {
                if (annotation instanceof Getter && isGetterMethod(method)) {
                    Attribute attr = getAttribute(((Getter) annotation).name());

                    Object attrParams = getAttrParams(((Getter) annotation).paramsClass());

                    if (attr == null) {
                        attr = new Attribute(method.getReturnType(), method.getName(), null, attrParams);

                        _attributes.put(((Getter) annotation).name(), attr);
                    } else {
                        attr.setGetter(method.getName());
                        attr.setAttributeClass(method.getReturnType());
                        if (attr.getParams() == null && attrParams != null)
                            attr.setParams(attrParams);
                    }
                } else if (annotation instanceof Setter && isSetterMethod(method)) {
                    _setters.put(method, ((Setter) annotation).name());

                    Attribute attr = getAttribute(((Setter) annotation).name());

                    Object attrParams = getAttrParams(((Setter) annotation).paramsClass());

                    if (attr == null) {
                        attr = new Attribute(method.getParameterTypes()[0], null, method.getName(), attrParams);

                        _attributes.put(((Setter) annotation).name(), attr);
                    } else {
                        attr.setSetter(method.getName());

                        if (attr.getAttributeClass() == null)
                            attr.setAttributeClass(method.getParameterTypes()[0]);
                        if (attr.getParams() == null && attrParams != null)
                            attr.setParams(attrParams);
                    }
                } else if (annotation instanceof Reader && isReaderMethod(method)) {
                    Attribute attr = getAttribute(((Reader) annotation).name());

                    Object attrParams = getAttrParams(((Reader) annotation).paramsClass());

                    if (attr == null) {
                        attr = new Attribute(method.getParameterTypes()[0], null, null, attrParams,
                                method.getName(), null);

                        _attributes.put(((Reader) annotation).name(), attr);
                    } else {
                        attr.setReader(method.getName());

                        if (attr.getAttributeClass() == null)
                            attr.setAttributeClass(method.getParameterTypes()[0]);
                        if (attr.getParams() == null && attrParams != null)
                            attr.setParams(attrParams);
                    }
                } else if (annotation instanceof Writer && isWriterMethod(method)) {
                    Attribute attr = getAttribute(((Writer) annotation).name());

                    Object attrParams = getAttrParams(((Writer) annotation).paramsClass());

                    if (attr == null) {
                        attr = new Attribute(method.getParameterTypes()[0], null, null, attrParams, null,
                                method.getName());

                        _attributes.put(((Writer) annotation).name(), attr);
                    } else {
                        attr.setWriter(method.getName());

                        if (attr.getAttributeClass() == null)
                            attr.setAttributeClass(method.getParameterTypes()[0]);
                        if (attr.getParams() == null && attrParams != null)
                            attr.setParams(attrParams);
                    }
                }

            }
    }
}

From source file:com.yahoo.elide.core.EntityBinding.java

public EntityBinding(Class<?> cls, String type) {
    // Map id's, attributes, and relationships
    Collection<AccessibleObject> fieldOrMethodList = CollectionUtils.union(Arrays.asList(cls.getFields()),
            Arrays.asList(cls.getMethods()));

    jsonApi = type;// w w  w  . jav  a  2  s.  c o  m
    // Initialize our maps for this entity. Duplicates are checked above.
    attrsDeque = new ConcurrentLinkedDeque<>();
    relationshipsDeque = new ConcurrentLinkedDeque<>();
    relationshipTypes = new ConcurrentHashMap<>();
    relationshipToInverse = new ConcurrentHashMap<>();
    fieldsToValues = new ConcurrentHashMap<>();
    fieldsToTypes = new ConcurrentHashMap<>();
    fieldsToTriggers = new MultiValueMap<>();
    aliasesToFields = new ConcurrentHashMap<>();
    accessibleObject = new ConcurrentHashMap<>();
    bindEntityFields(cls, type, fieldOrMethodList);
    bindAccessibleObjects(cls, fieldOrMethodList);

    attrs = dequeToList(attrsDeque);
    relationships = dequeToList(relationshipsDeque);
}

From source file:com.haulmont.restapi.config.RestServicesConfiguration.java

@Nullable
protected Method _findMethod(String serviceName, String methodName, List<RestMethodParamInfo> paramInfos) {
    List<Class> paramTypes = new ArrayList<>();
    for (RestMethodParamInfo paramInfo : paramInfos) {
        if (StringUtils.isNotEmpty(paramInfo.getType())) {
            try {
                paramTypes.add(ClassUtils.forName(paramInfo.getType(), null));
            } catch (ClassNotFoundException e) {
                log.error("Class {} for method parameter not found. Service: {}, method: {}, param: {}",
                        paramInfo.getType(), serviceName, methodName, paramInfo.getName());
                return null;
            }/*from   ww w.  ja v  a2s. com*/
        }
    }

    if (!paramTypes.isEmpty() && paramInfos.size() != paramTypes.size()) {
        log.error(
                "Service method parameters types must be defined for all parameters or for none of them. Service: {}, method: {}",
                serviceName, methodName);
        return null;
    }

    Object service = AppBeans.get(serviceName);
    Method serviceMethod = null;
    //the service object we get here is proxy. To get methods with type information
    //we need tp know actual interfaces implemented by the service (this is required when parameterized
    //collection of entities is passed as an argument)
    Class<?>[] serviceInterfaces = service.getClass().getInterfaces();
    if (serviceInterfaces.length == 0) {
        log.error("Service {} doesn't implement any interface. It cannot be user for the REST API",
                serviceName);
        return null;
    }

    if (paramTypes.isEmpty()) {
        List<Method> appropriateMethods = new ArrayList<>();
        for (Class<?> serviceInterface : serviceInterfaces) {
            //trying to guess which method to invoke
            Method[] methods = serviceInterface.getMethods();
            for (Method method : methods) {
                if (methodName.equals(method.getName())
                        && method.getParameterTypes().length == paramInfos.size()) {
                    appropriateMethods.add(method);
                }
            }
        }
        if (appropriateMethods.size() == 1) {
            serviceMethod = appropriateMethods.get(0);
        } else if (appropriateMethods.size() > 1) {
            log.error(
                    "There are multiple methods with given argument numbers. Parameters type must be defined. Service: {}, method: {}",
                    serviceName, methodName);
            return null;
        } else {
            log.error("Method not found. Service: {}, method: {}, number of arguments: {}", serviceName,
                    methodName, paramInfos.size());
            return null;
        }
    } else {
        for (Class<?> serviceInterface : serviceInterfaces) {
            try {
                serviceMethod = serviceInterface.getMethod(methodName,
                        paramTypes.toArray(new Class[paramTypes.size()]));
            } catch (NoSuchMethodException ignored) {
            }
        }
        if (serviceMethod == null) {
            log.error("Method not found. Service: {}, method: {}, argument types: {}", serviceName, methodName,
                    paramTypes);
            return null;
        }
    }
    return serviceMethod;
}

From source file:com.jsmartframework.web.manager.BeanHelper.java

Method[] getBeanMethods(Class<?> clazz) {
    if (!beanMethods.containsKey(clazz)) {
        beanMethods.put(clazz, clazz.getMethods());
    }//from  www .  j  ava  2  s . c o m
    return beanMethods.get(clazz);
}

From source file:io.smartspaces.workbench.project.test.JunitTestClassDetector.java

/**
 * Is the class a JUnit test class?//from   www  .j  a  v  a  2s. c om
 *
 * @param potentialTestClass
 *          the class to test
 * @param log
 *          the logger to use
 *
 * @return {@code true} if the class is testable and can be instantiated
 */
private boolean isTestClass(Class<?> potentialTestClass, Log log) {
    if (potentialTestClass.isInterface() || !classHasPublicConstructor(potentialTestClass, log)) {
        return false;
    }

    // Do not attempt to run tests on abstract test classes.
    if (Modifier.isAbstract(potentialTestClass.getModifiers())) {
        return false;
    }

    for (Method method : potentialTestClass.getMethods()) {
        if (method.isAnnotationPresent(Test.class)) {

            // No need to check any more if we have 1
            return true;
        }
    }

    return false;
}