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:org.paxml.util.ReflectUtils.java

/**
 * Set a property for a bean./*from  ww  w. ja  v a  2  s .  c  om*/
 * 
 * @param bean
 *            the bean
 * @param pd
 *            the property descriptor
 * @param value
 *            the property value
 */
public static void callSetter(Object bean, PropertyDescriptor pd, Object value) {

    Method setter = pd.getWriteMethod();
    if (setter == null) {
        throw new PaxmlRuntimeException(
                "Property '" + pd.getName() + "' is not settable on class: " + bean.getClass().getName());
    }

    value = coerceType(value, setter.getParameterTypes()[0]);
    try {
        setter.invoke(bean, value);
    } catch (Exception e) {
        throw new PaxmlRuntimeException("Cannot call setter on property: " + pd.getName(), e);
    }
}

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

private static Map<String, MethodHandle> methods(final RemoteJsonService impl) {
    final Class<? extends RemoteJsonService> d = findInterface(impl.getClass());
    if (d == null) {
        return Collections.<String, MethodHandle>emptyMap();
    }/*  w  w  w .ja va  2 s  . c o m*/

    final Map<String, MethodHandle> r = new HashMap<String, MethodHandle>();
    for (final Method m : d.getMethods()) {
        if (!Modifier.isPublic(m.getModifiers())) {
            continue;
        }

        if (m.getReturnType() != Void.TYPE) {
            continue;
        }

        final Class<?>[] params = m.getParameterTypes();
        if (params.length < 1) {
            continue;
        }

        if (!params[params.length - 1].isAssignableFrom(AsyncCallback.class)) {
            continue;
        }

        final MethodHandle h = new MethodHandle(impl, m);
        r.put(h.getName(), h);
    }
    return Collections.unmodifiableMap(r);
}

From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java

/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) 
 * @author Alex/*from  w  w  w .  j  av a 2 s  . co  m*/
 */
@SuppressWarnings("unchecked")
public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate,
        final Optional<QueryComponent<T>> extra_query,
        final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform,
        final Map<String, BiFunction<Object, Object[], Object>> interceptors,
        final Optional<BiFunction<Object, Object[], Object>> default_interceptor) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());

            // First off, apply the extra term to any relevant args:
            final Object[] args_with_extra_query_pretransform = query_transform.map(q -> {
                return (null != args) ? Arrays.stream(args)
                        .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                ? q.apply((QueryComponent<T>) o)
                                : o)
                        .collect(Collectors.toList()).toArray() : args;
            }).orElse(args);

            final Object[] args_with_extra_query = extra_query.map(q -> {
                return (null != args_with_extra_query_pretransform)
                        ? Arrays.stream(args_with_extra_query_pretransform)
                                .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                        ? CrudUtils.allOf((QueryComponent<T>) o, q)
                                        : o)
                                .collect(Collectors.toList()).toArray()
                        : args_with_extra_query_pretransform;
            }).orElse(args_with_extra_query_pretransform);

            // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId
            final Object o = Lambdas.get(() -> {
                final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz)
                        ? (SingleQueryComponent<T>) CrudUtils.allOf()
                        : CrudUtils.allOf(clazz);

                try {
                    if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec
                        return delegate.countObjectsBySpec(extra_query.get());
                    } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query
                        if (1 == args.length) {
                            return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(),
                                    base_query.when(JsonUtils._ID, args[0])));
                        } else {
                            return delegate.getObjectBySpec(
                                    CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                    (List<String>) args[1], (Boolean) args[2]);
                        }
                    } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) {
                        CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get());
                        return l.thenApply(ll -> ll > 0);
                    } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query
                        return delegate.deleteObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])));
                    } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query
                        return delegate.updateObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                Optional.empty(), (UpdateComponent<T>) args[1]);
                    } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        Optional<QueryComponent<JsonNode>> json_extra_query = extra_query
                                .map(qc -> qc.toJson());
                        return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query,
                                Optional.empty(), interceptors, default_interceptor);
                    } else { // wrap any CrudService types
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        return (null != o_internal)
                                && ICrudService.class.isAssignableFrom(o_internal.getClass())
                                        ? intercept(clazz, (ICrudService<T>) o_internal, extra_query,
                                                Optional.empty(), interceptors, default_interceptor)
                                        : o_internal;
                    }
                } catch (IllegalAccessException ee) {
                    throw new RuntimeException(ee);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getCause().getMessage(), e);
                }
            });

            return interceptors
                    .getOrDefault(m.getName(),
                            default_interceptor.orElse(CrudServiceUtils::identityInterceptor))
                    .apply(o, args_with_extra_query);
        }
    };

    return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass())
            ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(),
                    new Class[] { ICrudService.IReadOnlyCrudService.class }, handler)
            : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(),
                    new Class[] { ICrudService.class }, handler);
}

From source file:com.alibaba.rocketmq.common.MixAll.java

/**
 * PropertiesObject//w  ww.  ja  va  2 s . co m
 */
public static void properties2Object(final Properties p, final Object object) {
    Method[] methods = object.getClass().getMethods();
    for (Method method : methods) {
        String mn = method.getName();
        if (mn.startsWith("set")) {
            try {
                String tmp = mn.substring(4);
                String first = mn.substring(3, 4);

                String key = first.toLowerCase() + tmp;
                String property = p.getProperty(key);
                if (property != null) {
                    Class<?>[] pt = method.getParameterTypes();
                    if (pt != null && pt.length > 0) {
                        String cn = pt[0].getSimpleName();
                        Object arg = null;
                        if (cn.equals("int")) {
                            arg = Integer.parseInt(property);
                        } else if (cn.equals("long")) {
                            arg = Long.parseLong(property);
                        } else if (cn.equals("double")) {
                            arg = Double.parseDouble(property);
                        } else if (cn.equals("boolean")) {
                            arg = Boolean.parseBoolean(property);
                        } else if (cn.equals("String")) {
                            arg = property;
                        } else {
                            continue;
                        }
                        method.invoke(object, new Object[] { arg });
                    }
                }
            } catch (Throwable e) {
            }
        }
    }
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static void printMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            if (logger.isDebugEnabled() == true) {
                logger.debug("Printing out specifics for method: " + method.getName() + " with return type: "
                        + method.getReturnType().getName());
            }/*from   w  w  w .ja va  2 s .  c  o m*/

            for (int i = 0; i < method.getParameterTypes().length; i++) {
                if (logger.isDebugEnabled() == true) {
                    logger.debug("and with parameter type: " + method.getParameterTypes()[i]);
                }
            }

            return true;
        }
    };

    CollectionUtils.filter(methodList, mutatorPredicate);
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}/*from w w  w  . ja  va  2 s . c  o m*/
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:com.datatorrent.lib.util.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {// w  ww.j a va2  s.com
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:ch.aonyx.broker.ib.api.util.AnnotationUtils.java

/**
 * Get a single {@link Annotation} of <code>annotationType</code> from the supplied {@link Method}, traversing its
 * super methods if no annotation can be found on the given method itself.
 * <p>/*from  www  .ja v a2 s  .c  om*/
 * 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</code> if none found
 */
public static <A extends Annotation> A findAnnotation(final Method method, final Class<A> annotationType) {
    A annotation = getAnnotation(method, annotationType);
    Class<?> cl = method.getDeclaringClass();
    if (annotation == null) {
        annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
    }
    while (annotation == null) {
        cl = cl.getSuperclass();
        if ((cl == null) || (cl == Object.class)) {
            break;
        }
        try {
            final Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            annotation = getAnnotation(equivalentMethod, annotationType);
            if (annotation == null) {
                annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces());
            }
        } catch (final NoSuchMethodException ex) {
            // We're done...
        }
    }
    return annotation;
}

From source file:com.helpinput.utils.Utils.java

public static Method findMethod(Class<?> targetClass, String methodName, Class<?>[] agrsClasses) {
    Method[] methods = targetClass.getDeclaredMethods();
    Method theMethod = null;/*from w  w w .j  av a  2  s  . com*/

    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            Class<?>[] classes = method.getParameterTypes();

            if (agrsClasses.length == 0 && classes.length == 0) {
                theMethod = method;
                break;
            }

            if (agrsClasses.length == classes.length) {
                for (int i = 0; i < agrsClasses.length; i++) {
                    if (agrsClasses[i] == null) {
                        if (i == agrsClasses.length - 1) {
                            theMethod = method;
                            break;
                        }
                        continue;
                    }
                    if (classes[i].isPrimitive()) {
                        if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i]))
                            break;
                    } else if (!classes[i].isAssignableFrom(agrsClasses[i]))
                        break;
                    if (i == agrsClasses.length - 1) {
                        theMethod = method;
                        break;
                    }
                }
            }
            if (theMethod != null)
                break;
        }
        if (theMethod != null)
            break;
    }

    if (null != theMethod) {
        return accessible(theMethod);
    } else {
        if (targetClass.getSuperclass() != null) {
            return findMethod(targetClass.getSuperclass(), methodName, agrsClasses);
        }
        return null;
    }
}

From source file:com.springframework.core.annotation.AnnotationUtils.java

/**
 * Retrieve the given annotation's attributes as an {@link AnnotationAttributes}
 * map structure./* ww  w .  ja  va 2 s  .  com*/
 * <p>This method provides fully recursive annotation reading capabilities on par with
 * the reflection-based {@link org.springframework.core.type.StandardAnnotationMetadata}.
 * @param annotation the annotation to retrieve the attributes for
 * @param classValuesAsString whether to convert Class references into Strings (for
 * compatibility with {@link org.springframework.core.type.AnnotationMetadata})
 * or to preserve them as Class references
 * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
 * {@link AnnotationAttributes} maps (for compatibility with
 * {@link org.springframework.core.type.AnnotationMetadata}) or to preserve them as
 * Annotation instances
 * @return the annotation attributes (a specialized Map) with attribute names as keys
 * and corresponding attribute values as values; never {@code null}
 * @since 3.1.1
 */
public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString,
        boolean nestedAnnotationsAsMap) {

    AnnotationAttributes attrs = new AnnotationAttributes();
    Method[] methods = annotation.annotationType().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
            try {
                ReflectionUtils.makeAccessible(method);
                Object value = method.invoke(annotation);
                attrs.put(method.getName(), adaptValue(value, classValuesAsString, nestedAnnotationsAsMap));
            } catch (Exception ex) {
                throw new IllegalStateException("Could not obtain annotation attribute values", ex);
            }
        }
    }
    return attrs;
}