Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.capgemini.boot.core.factory.internal.SettingBackedBeanFactoryPostProcessor.java

private Map<String, List<Method>> getSettingBackedBeanMethods(Class<?> clazz) {
    final Map<String, List<Method>> settingMethods = new HashMap<String, List<Method>>();

    for (Method method : clazz.getDeclaredMethods()) {
        if (getProcessorStrategy().isFactoryMethod(method)) {
            final String setting = getProcessorStrategy().getSettingName(method);

            if (!settingMethods.containsKey(setting)) {
                settingMethods.put(setting, new ArrayList<Method>());
            }//ww w .  ja va2s.c o m

            settingMethods.get(setting).add(method);
        }
    }

    return settingMethods;
}

From source file:com.web.services.ExecutorServicesConstruct.java

/**
 * This method removes the configuration of the War file
 * @param servicesMap// w w  w  .ja  v  a 2s . c o  m
 * @param exectorServicesXml
 * @param customClassLoader
 * @throws Exception
 */
public void removeExecutorServices(Hashtable servicesMap, File exectorServicesXml,
        WebClassLoader customClassLoader) throws Exception {
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/executorservices-config.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    ExecutorServices executorServices = (ExecutorServices) serverdigester
            .parse(new InputSource(new FileInputStream(exectorServicesXml)));
    CopyOnWriteArrayList<ExecutorService> executorServicesList = executorServices.getExecutorServices();
    ExecutorServiceAnnot executorServiceAnnot;
    for (ExecutorService executorService : executorServicesList) {
        Class executorServiceClass = customClassLoader
                .loadClass(executorService.getExecutorserviceclass().toString());
        //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
        //System.out.println();
        Method[] methods = executorServiceClass.getDeclaredMethods();
        for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation instanceof ExecutorServiceAnnot) {
                    executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                    //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception();
                    servicesMap.remove(executorServiceAnnot.servicename());
                }
            }
        }
    }
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {/*from w  w w. j a v  a2  s . com*/
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

From source file:com.dianping.resource.io.util.ClassUtils.java

/**
 * Return the number of methods with a given name (with any argument types),
 * for the given class and/or its superclasses. Includes non-public methods.
 * @param clazz   the clazz to check/*from   www. j  a  v  a 2s. co m*/
 * @param methodName the name of the method
 * @return the number of methods with the given name
 */
public static int getMethodCountForName(Class<?> clazz, String methodName) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    int count = 0;
    Method[] declaredMethods = clazz.getDeclaredMethods();
    for (Method method : declaredMethods) {
        if (methodName.equals(method.getName())) {
            count++;
        }
    }
    Class<?>[] ifcs = clazz.getInterfaces();
    for (Class<?> ifc : ifcs) {
        count += getMethodCountForName(ifc, methodName);
    }
    if (clazz.getSuperclass() != null) {
        count += getMethodCountForName(clazz.getSuperclass(), methodName);
    }
    return count;
}

From source file:org.apache.sling.performance.FrameworkPerformanceMethod.java

/**
 * Retrieve all the specific methods from test class
 *
 * @param testClass//w  w w. j  av a2  s . co m
 *            the test class that we need to search in
 * @param annotation
 *            the annotation that we should look for
 * @return the list with the methods that have the specified annotation
 */
@SuppressWarnings({ "rawtypes" })
private Method[] getSpecificMethods(Class testClass, Class<? extends Annotation> annotation) {
    Method[] allMethods = testClass.getDeclaredMethods();

    List<Method> methodListResult = new ArrayList<Method>();

    for (Method testMethod : allMethods) {
        if (testMethod.isAnnotationPresent(annotation)) {
            methodListResult.add(testMethod);
        }
    }
    return methodListResult.toArray(new Method[] {});
}

From source file:org.apache.hadoop.hbase.tool.coprocessor.CoprocessorValidator.java

private void validate(ClassLoader classLoader, String className, List<CoprocessorViolation> violations) {
    LOG.debug("Validating class '{}'.", className);

    try {//from   w  w  w. j a  va 2 s. co m
        Class<?> clazz = classLoader.loadClass(className);

        for (Method method : clazz.getDeclaredMethods()) {
            LOG.trace("Validating method '{}'.", method);

            if (branch1.hasMethod(method) && !current.hasMethod(method)) {
                CoprocessorViolation violation = new CoprocessorViolation(className, Severity.WARNING,
                        "method '" + method
                                + "' was removed from new coprocessor API, so it won't be called by HBase");
                violations.add(violation);
            }
        }
    } catch (ClassNotFoundException e) {
        CoprocessorViolation violation = new CoprocessorViolation(className, Severity.ERROR, "no such class",
                e);
        violations.add(violation);
    } catch (RuntimeException | Error e) {
        CoprocessorViolation violation = new CoprocessorViolation(className, Severity.ERROR,
                "could not validate class", e);
        violations.add(violation);
    }
}

From source file:com.freetmp.common.util.ClassUtils.java

public static int getMethodCountForName(Class<?> clazz, String methodName) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    int count = 0;
    Method[] declaredMethods = clazz.getDeclaredMethods();
    for (Method method : declaredMethods) {
        if (methodName.equals(method.getName())) {
            count++;/*from ww w  .  jav a 2s .  c o  m*/
        }
    }
    Class<?>[] ifcs = clazz.getInterfaces();
    for (Class<?> ifc : ifcs) {
        count += getMethodCountForName(ifc, methodName);
    }
    if (clazz.getSuperclass() != null) {
        count += getMethodCountForName(clazz.getSuperclass(), methodName);
    }
    return count;
}

From source file:com.flipkart.phantom.thrift.impl.ThriftProxy.java

@SuppressWarnings("rawtypes")
public void setThriftServiceClass(String thriftServiceClass) {
    this.thriftServiceClass = thriftServiceClass;
    // Inspect and add ProcessFunction instances for all public methods on the declared service interface
    String serviceInterfaceClass = this.thriftServiceClass + "$" + DEFAULT_SERVICE_INTERFACE_NAME;
    try {/* w ww.ja  va  2  s .c om*/
        Class serviceClass = Class.forName(serviceInterfaceClass);
        Method[] methods = serviceClass.getDeclaredMethods();
        for (Method method : methods) {
            String processFunctionClass = this.thriftServiceClass + "$" + DEFAULT_PROCESSOR_CLASS_NAME + "$"
                    + method.getName();
            this.processMap.put(method.getName(),
                    (ProcessFunction) Class.forName(processFunctionClass).newInstance());
        }
    } catch (Exception e) {
        LOGGER.error("Unable to inspect specified Thrift service class. Error is : " + e.getMessage(), e);
        // empty the processMap. This will fail the init of this handler in #afterPropertiesSet()
        this.processMap.clear();
    }
}

From source file:com.nerve.commons.repository.utils.reflection.ReflectionUtils.java

/**
 *
 * ?annotationClass//  w  w w . j a v a  2 s  .c o  m
 *
 * @param targetClass
 *            Class
 * @param annotationClass
 *            Class
 *
 * @return List
 */
public static <T extends Annotation> List<T> getAnnotations(Class targetClass, Class annotationClass) {
    Assert.notNull(targetClass, "targetClass?");
    Assert.notNull(annotationClass, "annotationClass?");

    List<T> result = new ArrayList<T>();
    Annotation annotation = targetClass.getAnnotation(annotationClass);
    if (annotation != null) {
        result.add((T) annotation);
    }
    Constructor[] constructors = targetClass.getDeclaredConstructors();
    // ?
    CollectionUtils.addAll(result, getAnnotations(constructors, annotationClass).iterator());

    Field[] fields = targetClass.getDeclaredFields();
    // ?
    CollectionUtils.addAll(result, getAnnotations(fields, annotationClass).iterator());

    Method[] methods = targetClass.getDeclaredMethods();
    // ?
    CollectionUtils.addAll(result, getAnnotations(methods, annotationClass).iterator());

    for (Class<?> superClass = targetClass.getSuperclass(); superClass == null
            || superClass == Object.class; superClass = superClass.getSuperclass()) {
        List<T> temp = (List<T>) getAnnotations(superClass, annotationClass);
        if (CollectionUtils.isNotEmpty(temp)) {
            CollectionUtils.addAll(result, temp.iterator());
        }
    }

    return result;
}

From source file:com.angstoverseer.persistence.converter.GoogleAppEngineEntityConverter.java

@Override
public Object convert(Entity entity, Class klass) {
    log.debug("convert: {}, {}", entity, klass);

    final Object convertedInstance;
    try {/*from   w  w w. ja v  a  2  s. c  o  m*/
        convertedInstance = klass.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Unable to instantiate " + klass.getName(), e);
    }

    Method[] methods = klass.getDeclaredMethods();
    Map<String, Object> propertiesToBeSet = getPropertiesToBeSet(entity, methods);
    for (Method method : methods) {
        if (method.getName().startsWith("set")
                && propertiesToBeSet.containsKey(extractPropertyNameFromSetterMethod(method))) {
            log.debug("method.getName(): {}", method.getName());

            try {
                final Object newValue = propertiesToBeSet.get(extractPropertyNameFromSetterMethod(method));
                log.debug("newValue: {}", newValue);
                method.invoke(convertedInstance, newValue);
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to invoke method " + klass.getName() + "." + method.getName(), e);
            }
        }
    }

    return convertedInstance;
}