Example usage for java.lang.reflect Method getGenericParameterTypes

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

Introduction

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

Prototype

@Override
public Type[] getGenericParameterTypes() 

Source Link

Usage

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

private void setUpProviderState(Object testInstance, Workflow workflow) throws Exception {
    if (workflow.getProviderStates() != null) {
        for (Pact.ProviderState providerState : workflow.getProviderStates()) {
            if (testInstance instanceof ObjectStringConverterSource) {
                providerState.setJsonConverter(((ObjectStringConverterSource) testInstance).getConverter());
            } else {
                providerState.setJsonConverter(jsonConverter);
            }//from   w ww . j a v  a  2 s  .  com
            Method providerStateSetupMethod = providerStateMethods.get(providerState.getDescription());
            if (providerStateSetupMethod == null) {
                throw new IllegalStateException(
                        "Cannot find a setup method for provider state " + providerState.getDescription());
            }
            providerStateSetupMethod.invoke(testInstance,
                    providerState.getStates(providerStateSetupMethod.getGenericParameterTypes()));
        }
    }
}

From source file:com.sworddance.beans.ProxyMapperImpl.java

/**
 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
 *//*from w  w  w. ja v  a  2 s  . c o  m*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    String propertyName;
    ProxyMethodHelper methodHelper = getProxyMethodHelper();
    if (methodHelper != null && methodHelper.isHandling(this, proxy, method, args)) {
        return methodHelper.invoke(this, proxy, method, args);
    } else if (method.getGenericParameterTypes().length == 0
            && (propertyName = this.getGetterPropertyName(methodName)) != null) {
        if (this.containsKey(propertyName)) {
            return this.getCachedValue(propertyName);
        } else {
            switch (this.getProxyBehavior()) {
            case nullValue:
                return null;
            case readThrough:
            case leafStrict:
                if (method.getReturnType() == Void.class || args != null && args.length > 1) {
                    // or more than 1 argument (therefore not java bean property )
                    return doInvoke(method, args);
                } else {
                    return initValue(propertyName);
                }
            case strict:
                throw new ApplicationIllegalStateException("no cached value with strict proxy behavior. proxy=",
                        this, " method=", method, "(", join(args), ")");
            }
        }
        return null;
    } else if (method.getGenericParameterTypes().length == 1
            && (propertyName = this.getSetterPropertyName(methodName)) != null) {
        this.putNewValues(propertyName, args[0]);
        return null;
    } else {
        // HACK: how to handle sideeffects? (can't )
        switch (this.getProxyBehavior()) {
        case strict:
            throw new ApplicationIllegalStateException(this, " method=", method, "(", join(args), ")");
        default:
            return doInvoke(method, args);
        }
    }
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

@Override
public void handle(Mapping mapping, Call call) {
    Executor executor = call.getCurrent();

    Method executorMethod = executor.getMethod();
    String[] parameterNames = ReflectionUtils.getParameterNames(mapping, executorMethod);

    // Sort parameters and convert
    ParameterTree parameterTree = call.getParameterTree();
    Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray();
    Map<String, ParameterTree> parameterObject = parameterTree.getObject();

    Class<?>[] parameterTypes = executorMethod.getParameterTypes();
    Type[] genericParameterTypes = executorMethod.getGenericParameterTypes();
    List<String> protectedParameters = executor.getProtectedParameters();

    // Save object in call
    Map<String, Object> convertedParameters = executor.getParameters();

    for (int position = 0; position < parameterNames.length; position++) {
        String name = parameterNames[position];
        Class<?> type = parameterTypes[position];
        Type genericType = genericParameterTypes[position];

        if (!protectedParameters.contains(name)) {
            try {
                if (parameterArray != null) {
                    List<ParameterTree> array = parameterArray.get(name);
                    if (array != null) {
                        Object value = convert(array, type, genericType);
                        convertedParameters.put(name, value);
                    }/*from   w w w  .  ja v  a 2 s.  c om*/
                }

                if (parameterObject != null) {
                    ParameterTree object = parameterObject.get(name);

                    if (object == null && !Collection.class.isAssignableFrom(type)
                            && !Map.class.isAssignableFrom(type) && !UploadFile.class.isAssignableFrom(type)
                            && !File.class.isAssignableFrom(type) && !type.isArray()
                            && converter.lookup(type) == null) {

                        object = parameterTree;
                    }

                    if (object != null) {
                        Object value = convert(object, type, genericType);
                        convertedParameters.put(name, value);
                    }
                }

            } catch (Exception ex) {
                throw new WebMotionException(
                        "Error during converting parameter " + name + " before invoke the method", ex);
            }
        }
    }
}

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

private ParametersSetterBlockList createParametersSetterBlockList(JdbcTemplate jdbcTemplate,
        ParameterConverterService converterService, Method method, int listParameterIndex,
        StoredProcedureInfo aStoredProcedureInfo) {
    Class entityClass = getListEntityClass(method.getGenericParameterTypes()[listParameterIndex]);
    String tableName = getListTableName(entityClass);

    if (!tableName.matches("^[a-zA-Z0-9_]+$")) {
        // protecting ourselves from injection
        throw new IllegalStateException("Wrong temp table name: '" + tableName + "'");
    }//  w ww.  jav a 2 s.c  om

    if (LOG.isDebugEnabled()) {
        LOG.debug("Getting metadata for table {}...", tableName);
    }
    Map<String, Integer> types = createTypes(jdbcTemplate, tableName);
    List<IEntityArgumentGetter> getters = createListGetters("", entityClass, types, converterService,
            0 /* FROM FIRST PARAMETER */);
    String insertQuery = createListInsertQuery(getters, tableName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("insert query: {}", insertQuery);
    }
    String clearTableQuery = "delete from " + tableName;
    return new ParametersSetterBlockList(insertQuery, getters, clearTableQuery, listParameterIndex);
}

From source file:play.modules.swagger.PlayReader.java

private List<Annotation> getParamAnnotations(Class<?> cls, Method method, String simpleTypeName,
        int fieldPosition) {
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    List<Annotation> annotations = getParamAnnotations(cls, genericParameterTypes, paramAnnotations,
            simpleTypeName, fieldPosition);
    if (annotations != null) {
        return annotations;
    }/*from w  ww  .  j a va  2s. c  o  m*/

    // Fallback to type
    for (int i = 0; i < genericParameterTypes.length; i++) {
        annotations = getParamAnnotations(cls, genericParameterTypes, paramAnnotations, simpleTypeName, i);
        if (annotations != null) {
            return annotations;
        }
    }
    return null;
}

From source file:pl.bristleback.server.bristle.conf.resolver.action.ActionResolver.java

private boolean isDefaultRemoteAction(Class clazz, Method action) {
    if (!DefaultAction.class.isAssignableFrom(clazz)) {
        // this action class does not have default action
        return false;
    }//from  w w w  . jav a  2s  . c o  m
    Method defaultMethod = DefaultAction.class.getMethods()[0];
    if (!defaultMethod.getName().equals(action.getName())) {
        return false;
    }
    Class[] defaultParameterTypes = defaultMethod.getParameterTypes();
    if (defaultParameterTypes.length != action.getParameterTypes().length) {
        return false;
    }
    int parametersLength = defaultParameterTypes.length;
    for (int i = 0; i < parametersLength - 1; i++) {
        Class defaultParameterType = defaultParameterTypes[i];
        if (!defaultParameterType.isAssignableFrom(action.getParameterTypes()[i])) {
            return false;
        }
    }
    Type requiredLastParameterType = action.getGenericParameterTypes()[parametersLength - 1];
    Type actualLastParameterType = null;
    for (int i = 0; i < clazz.getInterfaces().length; i++) {
        Class interfaceOfClass = clazz.getInterfaces()[i];
        if (DefaultAction.class.equals(interfaceOfClass)) {
            Type genericInterface = clazz.getGenericInterfaces()[i];
            if (genericInterface instanceof ParameterizedType) {
                actualLastParameterType = ((ParameterizedType) (genericInterface)).getActualTypeArguments()[1];
            } else {
                actualLastParameterType = Object.class;
            }
        }
    }

    return requiredLastParameterType.equals(actualLastParameterType);
}

From source file:org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource.java

/**
 * @see org.openmrs.module.webservices.rest.web.resource.api.Converter#setProperty(java.lang.Object,
 *      java.lang.String, java.lang.Object)
 *//*from  w w w. j av  a2 s .  c o m*/
@Override
public void setProperty(Object instance, String propertyName, Object value) throws ConversionException {
    if (propertiesIgnoredWhenUpdating.contains(propertyName)) {
        return;
    }
    try {
        DelegatingResourceHandler<? extends T> handler;

        try {
            handler = getResourceHandler((T) instance);
        } catch (Exception e) {
            // this try/catch isn't really needed because of java erasure behaviour at run time.
            // but I'm putting in here just in case
            handler = this;
        }

        // try to find a @PropertySetter-annotated method
        Method annotatedSetter = findSetterMethod(handler, propertyName);
        if (annotatedSetter != null) {
            Type expectedType = annotatedSetter.getGenericParameterTypes()[1];
            value = ConversionUtil.convert(value, expectedType);
            annotatedSetter.invoke(handler, instance, value);
            return;
        }

        // we need the generic type of this property, not just the class
        Method setter = PropertyUtils.getPropertyDescriptor(instance, propertyName).getWriteMethod();
        value = ConversionUtil.convert(value, setter.getGenericParameterTypes()[0]);

        if (value instanceof Collection) {
            //We need to handle collections in a way that Hibernate can track.
            Collection<?> newCollection = (Collection<?>) value;
            Object oldValue = PropertyUtils.getProperty(instance, propertyName);
            if (oldValue instanceof Collection) {
                Collection collection = (Collection) oldValue;
                collection.clear();
                collection.addAll(newCollection);
            } else {
                PropertyUtils.setProperty(instance, propertyName, value);
            }
        } else {
            PropertyUtils.setProperty(instance, propertyName, value);
        }
    } catch (Exception ex) {
        throw new ConversionException(propertyName + " on " + instance.getClass(), ex);
    }
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ????//from w w  w . j a v  a  2 s. co  m
 * 
 * @param method
 * @return
 */
public Type[] getMethodParamTypes(Method method) {
    ClassEx cw = this;
    method = getRealMethod(method);
    if (method.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, method.getDeclaringClass());
        cw = new ClassEx(type);
    }
    Type[] types = method.getGenericParameterTypes();
    for (int i = 0; i < types.length; i++) {
        types[i] = BeanUtils.getBoundType(types[i], cw);
    }
    return types;
}

From source file:org.apache.struts2.json.JSONInterceptor.java

@SuppressWarnings("unchecked")
public RPCResponse invoke(Object object, Map data)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, JSONException,
        InstantiationException, NoSuchMethodException, IntrospectionException {

    RPCResponse response = new RPCResponse();

    // validate id
    Object id = data.get("id");
    if (id == null) {
        String message = "'id' is required for JSON RPC";
        response.setError(new RPCError(message, RPCErrorCode.METHOD_NOT_FOUND));
        return response;
    }//from ww  w  .  j a va  2 s .  c om
    // could be a numeric value
    response.setId(id.toString());

    // the map is going to have: 'params', 'method' and 'id' (for the
    // client to identify the response)
    Class clazz = object.getClass();

    // parameters
    List parameters = (List) data.get("params");
    int parameterCount = parameters != null ? parameters.size() : 0;

    // method
    String methodName = (String) data.get("method");
    if (methodName == null) {
        String message = "'method' is required for JSON RPC";
        response.setError(new RPCError(message, RPCErrorCode.MISSING_METHOD));
        return response;
    }

    Method method = this.getMethod(clazz, methodName, parameterCount);
    if (method == null) {
        String message = "Method " + methodName + " could not be found in action class.";
        response.setError(new RPCError(message, RPCErrorCode.METHOD_NOT_FOUND));
        return response;
    }

    // parameters
    if (parameterCount > 0) {
        Class[] parameterTypes = method.getParameterTypes();
        Type[] genericTypes = method.getGenericParameterTypes();
        List invocationParameters = new ArrayList();

        // validate size
        if (parameterTypes.length != parameterCount) {
            // size mismatch
            String message = "Parameter count in request, " + parameterCount
                    + " do not match expected parameter count for " + methodName + ", " + parameterTypes.length;

            response.setError(new RPCError(message, RPCErrorCode.PARAMETERS_MISMATCH));
            return response;
        }

        // convert parameters
        for (int i = 0; i < parameters.size(); i++) {
            Object parameter = parameters.get(i);
            Class paramType = parameterTypes[i];
            Type genericType = genericTypes[i];

            // clean up the values
            if (dataCleaner != null) {
                parameter = dataCleaner.clean("[" + i + "]", parameter);
            }

            Object converted = populator.convert(paramType, genericType, parameter, method);
            invocationParameters.add(converted);
        }

        response.setResult(method.invoke(object, invocationParameters.toArray()));
    } else {
        response.setResult(method.invoke(object, new Object[0]));
    }

    return response;
}

From source file:org.romaframework.core.schema.reflection.SchemaClassReflection.java

public boolean initSetterForField(Method method, ParameterizedType owner) {
    String fieldName = method.getName();
    if (!fieldName.startsWith(SET_METHOD) || !checkIfFirstCharAfterPrefixIsUpperCase(fieldName, SET_METHOD))
        return false;
    if (method.getParameterTypes() != null && method.getParameterTypes().length != 1)
        return false;

    fieldName = firstToLower(fieldName.substring(SET_METHOD.length()));
    Class<?> javaFieldClass = SchemaHelper.resolveClassFromType(method.getGenericParameterTypes()[0], owner);
    SchemaFieldReflection fieldInfo = (SchemaFieldReflection) getField(fieldName);
    if (fieldInfo == null) {
        fieldInfo = createField(fieldName, javaFieldClass);
        fieldInfo.setterMethod = method;
    } else if (fieldInfo instanceof SchemaFieldReflection) {
        if (fieldInfo instanceof SchemaFieldDelegate
                && !javaFieldClass.isAssignableFrom(((SchemaFieldReflection) fieldInfo).getLanguageType())) {
            fieldInfo = createField(fieldName, javaFieldClass);
            fieldInfo.setterMethod = method;
        } else {//w w  w.  j  a v  a 2 s . c o m
            if (((SchemaFieldReflection) fieldInfo).getLanguageType().isAssignableFrom(javaFieldClass)) {
                fieldInfo.setterMethod = method;
                fieldInfo.setType(Roma.schema().getSchemaClassIfExist(javaFieldClass));
            }
        }
    }
    return true;

}