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:com.crossbusiness.resiliency.aspect.AbstractFallbackAspect.java

public Object rerouteToFallback(ProceedingJoinPoint pjp, Fallback fallbackConfig) throws Throwable {

    String[] fallbacks = fallbackConfig.value();
    Class<? extends Throwable>[] fallbackableExceptions = fallbackConfig.exceptions();

    List<Object> fallbackBeans = new ArrayList<Object>(fallbacks.length);
    for (String fallback : fallbacks) {
        try {/*from   w  ww .  ja  v  a2s .  co  m*/
            fallbackBeans.add(context.getBean(fallback));
        } catch (BeansException be) {
            log.error("configuration error: cannot find bean with name: '{}'", fallback, be);
            //configuration errors should be fixed immediately.    
            throw be;
        }
    }

    MethodSignature targetMethodSig = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSig.getMethod();
    Class[] paramTypes = (Class[]) targetMethod.getParameterTypes();
    Object[] args = pjp.getArgs();

    log.debug("fallbacks: {} method: '{}'", fallbacks, targetMethod);

    try {
        return pjp.proceed();
    } catch (Throwable t) {

        // if the exception is not what we're looking for, rethrow it
        if (!isFallbackableException(t, fallbackableExceptions))
            throw t;

        log.debug("got exception while trying the targetBean method: '{}'. will try fallbackBean...",
                targetMethod);
        Iterator<Object> iter = fallbackBeans.iterator();
        while (iter.hasNext()) {
            Object fallbackBean = iter.next();
            Method fallbackMethod;
            try {
                fallbackMethod = fallbackBean.getClass().getMethod(targetMethod.getName(), paramTypes);
            } catch (NoSuchMethodException | SecurityException nsme) {
                log.error(
                        "configuration error: No matchig method found in fallbackBean: '{}' that matches to targetBean method: '{}'",
                        new Object[] { fallbackBean.getClass().getName(), targetMethod, nsme });
                //configuration errors should be fixed immediately.   
                throw nsme;
            }
            try {
                log.debug("trying fallbackBean method: '{}'...", fallbackMethod);
                return fallbackMethod.invoke(fallbackBean, args);
            } catch (IllegalArgumentException | IllegalAccessException iae) {
                log.error(
                        "configuration error: arguments missmatch: fallbackBean method: '{}' arguments  missmatch to targetBean method: '{}' arguments",
                        new Object[] { fallbackMethod, targetMethod, iae });
                //configuration errors should be fixed immediately.   
                throw iae;
            } catch (InvocationTargetException ite) {
                log.debug(
                        "got exception while trying the fallbackBean method: '{}'. will try next fallbackBean...",
                        fallbackMethod);
                //fallbackBean method thrown an exception. try next bean or throw exception if this is the last bean
                if (!iter.hasNext()) {
                    //TODO : do we still need to check isFallbackableException?
                    throw ite.getCause();
                }
            }
        }
        //code should never reach this line. 
        throw t;
    }
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
    Method result = null;/* ww w .  java  2s  .  c  om*/
    final PropertyDescriptor propertyDescriptor = findPropertyDescriptorFor(clazz, propertyName);
    if (propertyDescriptor != null) {
        result = propertyDescriptor.getWriteMethod();
    }
    if (result == null) {
        Class<?> current = clazz;
        final String setterName = "set" + StringUtils.capitalize(propertyName);
        while (result == null && !Object.class.equals(current)) {
            final Method[] potentialMethods = current.getDeclaredMethods();
            for (Method potentialMethod : potentialMethods) {
                if (setterName.equals(potentialMethod.getName())) {
                    if (potentialMethod.getParameterTypes().length == 1) {
                        if (!mustBeStatic || Modifier.isStatic(potentialMethod.getModifiers())) {
                            if (!potentialMethod.isAccessible()) {
                                potentialMethod.setAccessible(true);
                            }
                            result = potentialMethod;
                        }
                    }
                }
            }
            current = current.getSuperclass();
        }
    }
    return result;
}

From source file:au.edu.anu.metadatastores.service.search.DisplayPage.java

/**
 * Get the page/*from   w  w  w  .  j  a  v  a2 s.c o  m*/
 * 
 * @param obj The object
 * @return The viewable
 */
public Viewable getPage(Object obj) throws Exception {
    for (Method method : DisplayPage.class.getMethods()) {
        if (method.getName().equals("getPage") && method.getParameterTypes()[0] == obj.getClass()) {
            try {
                Viewable returnObj = (Viewable) method.invoke(this, obj);
                return returnObj;
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof AccessDeniedException) {
                    throw new AccessDeniedException(e.getCause().getMessage());
                } else {
                    LOGGER.info("Error invoking method");
                    throw e;
                }
            }
        }
    }

    throw new RuntimeException("Cannot get the page for the class " + obj.getClass().getName());
}

From source file:com.github.tddts.jet.config.spring.postprocessor.MessageAnnotationBeanPostProcessor.java

private boolean checkMethod(Method method, Class<?> type) {
    if (!method.isAnnotationPresent(Message.class)) {
        return false;
    }//from  w  ww.j  av a 2  s.com
    if (method.getParameterCount() == 1 && method.getParameterTypes()[0].equals(String.class)) {
        return true;
    }
    logger.warn("Method [" + type + "." + method.getName()
            + "] is not populated with message. Method should have a single String parameter.");
    return false;
}

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

private boolean isCreateEntityMethod(Method daoMethod, StoredProcedureInfo procedureInfo) {
    boolean ok = false;
    if (procedureInfo.getArgumentsCounts() >= 1) {
        if (daoMethod.getParameterTypes().length == 1
                && !BlockFactoryUtils.isSimpleOrListType(daoMethod.getParameterTypes()[0])) {
            ok = true;/*from  w ww .j a v a2  s  .co m*/
        } else {
            if (daoMethod.getParameterTypes().length > 1) {
                // maybe it's entity + lists
                int entities = 0;
                int lists = 0;
                for (int i = 0; i < daoMethod.getParameterTypes().length; i++) {
                    if (!BlockFactoryUtils.isSimpleOrListType(daoMethod.getParameterTypes()[i])) {
                        entities++;
                    }
                    if (BlockFactoryUtils.isListType(daoMethod.getParameterTypes()[i])) {
                        lists++;
                    }
                }
                if (entities == 1 && lists > 0) {
                    // yes, it is
                    ok = true;
                }
            }
        }
        return ok;
    }
    return procedureInfo.getArgumentsCounts() >= 1 && daoMethod.getParameterTypes().length == 1
            && !BlockFactoryUtils.isSimpleType(daoMethod.getParameterTypes()[0]);
}

From source file:com.gzj.tulip.jade.statement.JdbcStatement.java

public JdbcStatement(StatementMetaData statementMetaData, SQLType sqlType, Interpreter[] interpreters,
        Querier querier) {/*from   w  w w .  j av a 2  s. c  o  m*/
    this.metaData = statementMetaData;
    AfterInvocation afterInvocationAnnotation = metaData.getMethod().getAnnotation(AfterInvocation.class);
    if (afterInvocationAnnotation != null) {
        try {
            this.afterInvocationCallback = afterInvocationAnnotation.value().newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    } else {
        this.afterInvocationCallback = nullAfterInvocationCallback;
    }
    this.interpreters = (interpreters == null) ? new Interpreter[0] : interpreters;
    this.querier = querier;
    this.sqlType = sqlType;
    if (sqlType == SQLType.WRITE) {
        Method method = statementMetaData.getMethod();
        Class<?>[] types = method.getParameterTypes();
        Class<?> returnType = statementMetaData.getReturnType();
        if (returnType.isPrimitive()) {
            returnType = ClassUtils.primitiveToWrapper(returnType);
        }

        //change by guozijian 2016-2-09-29
        //?SQL???
        //???updateinsert???
        SQL sqlAnnotation = method.getAnnotation(SQL.class);
        if (types.length > 0 && List.class.isAssignableFrom(types[0]) && (sqlAnnotation == null // @SQL
                || StringUtils.isBlank(sqlAnnotation.value()))) // SQL
        {
            //TODO ?List?????
            //if (types.length > 0 && List.class.isAssignableFrom(types[0])) {
            this.batchUpdate = true;
            if (metaData.getMethod().getAnnotation(ReturnGeneratedKeys.class) != null) {
                // ????@ReturnGeneratedKeys
                throw new InvalidDataAccessApiUsageException(
                        "batch update method cannot return generated keys: " + method);
            }
            if (returnType != void.class && returnType != int[].class //
                    && returnType != Integer.class && returnType != Boolean.class) {
                throw new InvalidDataAccessApiUsageException(
                        "error return type, only support type of {void,boolean,int,int[]}: " + method);
            }
        } else {
            this.batchUpdate = false;
            if (metaData.getMethod().getAnnotation(ReturnGeneratedKeys.class) != null) {
                metaData.getReturnGeneratedKeys().checkMethodReturnType(metaData.getReturnType(), metaData);
            } else if (returnType != void.class && returnType != Boolean.class && returnType != Integer.class) {
                throw new InvalidDataAccessApiUsageException(
                        "error return type, only support type of {void,boolean,int}:" + method);
            }
        }
    } else {
        this.batchUpdate = false;
    }
    this.logPrefix = "\n @method:" + this.metaData;
}

From source file:org.jboss.spring.support.SpringInjectionSupport.java

private boolean isSetterMethod(Method m) {
    return m.getName().startsWith("set") && m.getParameterTypes().length == 1;
}

From source file:com.amazonaws.services.kinesis.clientlibrary.config.KinesisClientLibConfigurator.java

private void withProperty(String propertyKey, Properties properties, KinesisClientLibConfiguration config) {
    if (propertyKey.isEmpty()) {
        throw new IllegalArgumentException("The property can't be empty string");
    }//from w  w  w. j  a va  2  s . c  om
    // Assume that all the setters in KinesisClientLibConfiguration are in the following format
    // They all start with "with" followed by the variable name with first letter capitalized
    String targetMethodName = PREFIX + Character.toUpperCase(propertyKey.charAt(0)) + propertyKey.substring(1);
    String propertyValue = properties.getProperty(propertyKey);
    if (nameToMethods.containsKey(targetMethodName)) {
        for (Method method : nameToMethods.get(targetMethodName)) {
            if (method.getParameterTypes().length == 1 && method.getName().equals(targetMethodName)) {
                Class<?> paramType = method.getParameterTypes()[0];
                if (classToDecoder.containsKey(paramType)) {
                    IPropertyValueDecoder<?> decoder = classToDecoder.get(paramType);
                    try {
                        method.invoke(config, decoder.decodeValue(propertyValue));
                        LOG.info(String.format("Successfully set property %s with value %s", propertyKey,
                                propertyValue));
                        return;
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        // At this point, we really thought that we could call this method.
                        LOG.warn(String.format("Encountered an error while invoking method %s with value %s. "
                                + "Exception was %s", method, propertyValue, e));
                    } catch (UnsupportedOperationException e) {
                        LOG.warn(String.format("The property %s is not supported as type %s at this time.",
                                propertyKey, paramType));
                    }
                } else {
                    LOG.debug(
                            String.format("No method for decoding parameters of type %s so method %s could not "
                                    + "be invoked.", paramType, method));
                }
            } else {
                LOG.debug(
                        String.format(
                                "Method %s doesn't look like it is appropriate for setting property %s. "
                                        + "Looking for something called %s.",
                                method, propertyKey, targetMethodName));
            }
        }
    } else {
        LOG.debug(
                String.format("There was no appropriately named method for setting property %s.", propertyKey));
    }
}

From source file:com.jredrain.dao.BeanResultTransFormer.java

/**
 * Setter/*from ww  w .j  a va  2s  . c om*/
 *
 * @param method
 * @return
 */
boolean filter(Method method) {
    if (method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 1) {
        String methodName = method.getName();
        return methodName.startsWith("set") && methodName.length() > 3;
    }
    return false;
}

From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java

private void ensureConverterMethodIsValid(final Class<?> type, final Method method)
        throws IllegalArgumentException {
    final Class<?>[] parameterTypes = method.getParameterTypes();
    final boolean hasCorrectParameters = (parameterTypes != null) && ((parameterTypes.length == 1)
            || ((parameterTypes.length == 2) && Exchange.class.isAssignableFrom(parameterTypes[1])));
    if (!hasCorrectParameters) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName()/*  www  . j  a  v  a  2s.c om*/
                + "]: a converter method must have exactly one parameter, or it must have exactly "
                + "two parameters where the second parameter is of type [" + Exchange.class.getName() + "].");
    }

    final int modifiers = method.getModifiers();
    if (isAbstract(modifiers) || !isPublic(modifiers)) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName() + "]: a converter method must not be abstract, and it must be public.");
    }

    final Class<?> toType = method.getReturnType();
    if (toType.equals(Void.class)) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName() + "]: a converter method must not return void.");
    }
}