Example usage for java.lang.reflect Method getParameterTypes

List of usage examples for java.lang.reflect Method getParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getParameterTypes.

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:net.roboconf.target.docker.internal.DockerUtils.java

/**
 * Finds the options and tries to configure them on the creation command.
 * @param options the options (key = name, value = option value)
 * @param cmd a non-null command to create a container
 * @throws TargetException/*from   w w w. j  av a  2 s.co  m*/
 */
public static void configureOptions(Map<String, String> options, CreateContainerCmd cmd)
        throws TargetException {

    Logger logger = Logger.getLogger(DockerUtils.class.getName());

    // Basically, we had two choices:
    // 1. Map our properties to the Java REST API.
    // 2. By-pass it and send our custom JSon object.
    //
    // The second option is much more complicated.
    // So, we use Java reflection and some hacks to match Docker properties
    // with the setter methods available in the API. The API remains in charge
    // of generating the right JSon objects.
    Map<String, List<String>> hackedSetterNames = new HashMap<>();

    // Remains from Docker-Java 2.x (the mechanism still works)
    //
    //      List<String> list = new ArrayList<> ();
    //      list.add( "withMemoryLimit" );
    //      hackedSetterNames.put( "withMemory", list );

    // List known types
    List<Class<?>> types = new ArrayList<>();
    types.add(String.class);
    types.add(String[].class);
    types.add(long.class);
    types.add(Long.class);
    types.add(int.class);
    types.add(Integer.class);
    types.add(boolean.class);
    types.add(Boolean.class);
    types.add(Capability[].class);

    // Deal with the options
    for (Map.Entry<String, String> entry : options.entrySet()) {
        String optionValue = entry.getValue();

        // Now, guess what option to set
        String methodName = entry.getKey().replace("-", " ").trim();
        methodName = WordUtils.capitalize(methodName);
        methodName = methodName.replace(" ", "");
        methodName = "with" + methodName;

        Method _m = null;
        for (Method m : cmd.getClass().getMethods()) {

            boolean sameMethod = methodName.equalsIgnoreCase(m.getName());
            boolean methodWithAlias = hackedSetterNames.containsKey(methodName)
                    && hackedSetterNames.get(methodName).contains(m.getName());

            if (sameMethod || methodWithAlias) {

                // Only one parameter?
                if (m.getParameterTypes().length != 1) {
                    logger.warning("A method was found for " + entry.getKey()
                            + " but it does not have the right number of parameters.");
                    continue;
                }

                // The right type?
                if (!types.contains(m.getParameterTypes()[0])) {

                    // Since Docker-java 3.x, there are two methods to set cap-add and cap-drop.
                    // One takes an array as parameter, the other takes a list.
                    logger.warning("A method was found for " + entry.getKey()
                            + " but it does not have the right parameter type. "
                            + "Skipping it. You may want to add a feature request.");

                    continue;
                }

                // That's probably the right one.
                _m = m;
                break;
            }
        }

        // Handle errors
        if (_m == null)
            throw new TargetException(
                    "Nothing matched the " + entry.getKey() + " option in the REST API. Please, report it.");

        // Try to set the option in the REST client
        try {
            Object o = prepareParameter(optionValue, _m.getParameterTypes()[0]);
            _m.invoke(cmd, o);

        } catch (ReflectiveOperationException | IllegalArgumentException e) {
            throw new TargetException("Option " + entry.getKey() + " could not be set.");
        }
    }
}

From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java

/**
 * Get a single {@link java.lang.annotation.Annotation} of {@code annotationType} from the supplied {@link java.lang.reflect.Method},
 * traversing its super methods if no annotation can be found on the given method itself.
 * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly.
 * @param method the method to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 *//*from   www.ja v a  2s.  co m*/
public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> clazz = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
    }
    while (annotation == null) {
        clazz = clazz.getSuperclass();
        if (clazz == null || clazz.equals(Object.class)) {
            break;
        }
        try {
            Method equivalentMethod = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
        } catch (NoSuchMethodException ex) {
            // No equivalent method found
        }
        if (annotation == null) {
            annotation = searchOnInterfaces(method, annotationType, clazz.getInterfaces());
        }
    }
    return annotation;
}

From source file:com.swingtech.commons.util.ClassUtil.java

public static String getMethodDeclarationString(final Method method) {
    final StringBuffer retStringBuff = new StringBuffer();

    retStringBuff.append(ClassUtil.getClassNameFromFullPath(method.getReturnType()));
    retStringBuff.append(" ");
    retStringBuff.append(ClassUtil.getClassNameFromFullPath(method.getDeclaringClass()));
    retStringBuff.append(".");
    retStringBuff.append(method.getName());
    retStringBuff.append("(");

    if (!Utility.isNullOrEmpty(method.getParameterTypes())) {
        Class c = null;//from  w w w. j  a v  a2  s .c  o  m
        for (int index = 0; index < method.getParameterTypes().length; index++) {
            c = method.getParameterTypes()[0];
            if (index > 1) {
                retStringBuff.append(", ");
            }
            retStringBuff.append(ClassUtil.getClassNameFromFullPath(c));
            retStringBuff.append(" arg" + index);
        }
    }

    retStringBuff.append(")");

    return retStringBuff.toString();
}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

public static Integer findIdParameterIndex(Method theMethod, FhirContext theContext) {
    Integer index = MethodUtil.findParamAnnotationIndex(theMethod, IdParam.class);
    if (index != null) {
        Class<?> paramType = theMethod.getParameterTypes()[index];
        if (IIdType.class.equals(paramType)) {
            return index;
        }/*from  w  w  w. j a v  a2 s . co m*/
        boolean isRi = theContext.getVersion().getVersion().isRi();
        boolean usesHapiId = IdDt.class.equals(paramType);
        if (isRi == usesHapiId) {
            throw new ConfigurationException(
                    "Method uses the wrong Id datatype (IdDt / IdType) for the given context FHIR version: "
                            + theMethod.toString());
        }
    }
    return index;
}

From source file:com.pandich.dropwizard.curator.refresh.MethodRefresher.java

@Override
protected Class<?> getType(final Method element) {
    return element.getParameterTypes()[0];
}

From source file:com.inspiresoftware.lib.dto.geda.interceptor.impl.TransferableUtils.java

private static Map<Occurrence, AdviceConfig> resolveConfiguration(final Method method,
        final Class<?> targetClass, final boolean trySpecific) {

    Method specificMethod = method;
    Transferable annotation = specificMethod.getAnnotation(Transferable.class);

    if (annotation == null && trySpecific) {

        specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
        annotation = specificMethod.getAnnotation(Transferable.class);

    }/*from w w w.  j a v  a  2  s  .  c  o  m*/

    if (annotation == null) {
        return Collections.emptyMap();
    }

    final Map<Occurrence, AdviceConfig> cfg = new HashMap<Occurrence, AdviceConfig>();
    resolveConfiguration(cfg, specificMethod.getName(), specificMethod.getParameterTypes(),
            specificMethod.getReturnType(), annotation);
    return cfg;

}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

/**
 * Attempt to find a {@link Method} on the supplied class with the supplied
 * name and parameter types. Searches all superclasses up to {@code Object}.
 * <p>/*  w w w.  j  a v  a2  s  .c  om*/
 * Returns {@code null} if no {@link Method} can be found.
 * 
 * @param clazz
 *            the class to introspect
 * @param name
 *            the name of the method
 * @param paramTypes
 *            the parameter types of the method (may be {@code null} to
 *            indicate any signature)
 * @return the Method object, or {@code null} if none found
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(name, "Method name must not be null");
    Class<?> searchType = clazz;
    while (searchType != null) {
        Method[] methods = (searchType.isInterface() ? searchType.getMethods()
                : getDeclaredMethods(searchType));
        for (Method method : methods) {
            if (name.equals(method.getName())
                    && (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
                return method;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.ryantenney.metrics.spring.GaugeMethodAnnotationBeanPostProcessor.java

@Override
protected void withMethod(final Object bean, String beanName, Class<?> targetClass, final Method method) {
    if (method.getParameterTypes().length > 0) {
        throw new IllegalStateException(
                "Method " + method.getName() + " is annotated with @Gauge but requires parameters.");
    }// w  w  w  .ja v a  2s  . co  m

    final Gauge annotation = method.getAnnotation(Gauge.class);
    final String metricName = Util.forGauge(targetClass, method, annotation);

    metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
        @Override
        public Object getValue() {
            return ReflectionUtils.invokeMethod(method, bean);
        }
    });

    LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
            method.getName());
}

From source file:com.ryantenney.metrics.spring.CachedGaugeAnnotationBeanPostProcessor.java

@Override
protected void withMethod(final Object bean, String beanName, Class<?> targetClass, final Method method) {
    if (method.getParameterTypes().length > 0) {
        throw new IllegalStateException(
                "Method " + method.getName() + " is annotated with @CachedGauge but requires parameters.");
    }/* w  w  w  .j  a va  2s.  c om*/

    final CachedGauge annotation = method.getAnnotation(CachedGauge.class);
    final String metricName = Util.forCachedGauge(targetClass, method, annotation);

    metrics.register(metricName,
            new com.codahale.metrics.CachedGauge<Object>(annotation.timeout(), annotation.timeoutUnit()) {
                @Override
                protected Object loadValue() {
                    return ReflectionUtils.invokeMethod(method, bean);
                }
            });

    LOG.debug("Created cached gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
            method.getName());
}

From source file:io.stallion.reflection.PropertyUtils.java

/**
 * Set a direct property on the target object. Conversions from propertyValue to the proper destination type
 * are performed whenever possible./*from  w w  w  .  ja  v  a  2s. c om*/
 *
 * @param target the target object on which to set the property.
 * @param propertyName the name of the property to set.
 * @param propertyValue the value of the property to set.
 * @throws PropertyException if an error happened while trying to set the property.
 */
private static void setDirectProperty(Object target, String propertyName, Object propertyValue)
        throws PropertyException {
    Method setter = getSetter(target, propertyName);
    if (setter == null && !(target instanceof Map)) {
        throw new PropertyException(
                "no writable setter for '" + propertyName + "' in class '" + target.getClass().getName() + "'");
    }
    Object transformedPropertyValue = propertyValue;
    if (setter != null && propertyValue != null) {
        Class parameterType = setter.getParameterTypes()[0];
        if (parameterType != null) {
            transformedPropertyValue = transform(propertyValue, parameterType);
        }
    }
    try {
        if (propertyValue != null) {
            if (setter == null) {
                ((Map) target).put(propertyName, transformedPropertyValue);
            } else {
                setter.invoke(target, new Object[] { transformedPropertyValue });
            }
        } else {
            if (setter == null) {
                ((Map) target).put(propertyName, transformedPropertyValue);
            } else {
                setter.invoke(target, new Object[] { null });
            }
        }
    } catch (IllegalAccessException ex) {
        throw new PropertyException("property '" + propertyName + "' is not accessible", ex);
    } catch (InvocationTargetException ex) {
        throw new PropertyException("property '" + propertyName + "' access threw an exception", ex);
    } catch (Exception ex) {
        String msg = "Error setting property " + target.getClass().getSimpleName() + "." + propertyName
                + " to value " + transformedPropertyValue;
        throw new PropertyException(msg, ex);
    }
}