Example usage for java.lang.reflect ParameterizedType getActualTypeArguments

List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getActualTypeArguments.

Prototype

Type[] getActualTypeArguments();

Source Link

Document

Returns an array of Type objects representing the actual type arguments to this type.

Usage

From source file:org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.java

private TypeDescription buildIterableTypeDescription(Member member, final Class<?> type) {
    final TypeDescription typeDescription = new TypeDescription(new TypeName(type));
    typeDescription.setIterable(true);/*from  w  w  w . jav  a 2s  .  co  m*/
    if (methodReturnTypeHasNoParameterInfo(member)) {
        // not a ParameterizedType, i.e. no parameter information => use Object as element type.
        typeDescription.setElementTypeName(new TypeName(Object.class));
        return typeDescription;
    }
    ParameterizedType parameterizedType = getParameterizedTypeOf(member);
    if (parameterizedType.getActualTypeArguments()[0] instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) parameterizedType.getActualTypeArguments()[0];
        typeDescription.setElementTypeName(new TypeName(genericArrayType.toString()));
        return typeDescription;
    }
    // Due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7151486,
    // java 7 is not able to detect GenericArrayType correctly => let's use a different way to detect array
    Class<?> internalClass = ClassUtil.getClass(parameterizedType.getActualTypeArguments()[0]);
    if (internalClass.isArray()) {
        String componentTypeWithoutClassPrefix = remove(internalClass.getComponentType().toString(), "class ");
        typeDescription.setElementTypeName(new TypeName(componentTypeWithoutClassPrefix + "[]"));
    } else {
        typeDescription.setElementTypeName(new TypeName(internalClass));
    }
    return typeDescription;
}

From source file:com.rest4j.impl.MapApiTypeImpl.java

@Override
public boolean check(Type javaType) {
    Class clz = Util.getClass(javaType);
    if (clz == null)
        return false;
    if (clz != Map.class && clz != HashMap.class && clz != LinkedHashMap.class)
        return false;
    if (javaType instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) javaType;
        if (pType.getActualTypeArguments().length != 2)
            return false;
        // the first parameter is a string
        if (!stringApiType.check(pType.getActualTypeArguments()[0]))
            return false;
        // the second parameter is the element type
        return elementType.check(pType.getActualTypeArguments()[1]);
    } else {/*from ww w. j av a  2s  .co  m*/
        return false;
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

public static Class<?> getGenericClass(Class<?> cls, int i) {
    try {// w w  w .  ja  v a2 s.co m
        ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        Object genericClass = parameterizedType.getActualTypeArguments()[i];
        if (genericClass instanceof ParameterizedType) { // ?
            return (Class<?>) ((ParameterizedType) genericClass).getRawType();
        } else if (genericClass instanceof GenericArrayType) { // ?
            return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
        } else {
            return (Class<?>) genericClass;
        }
    } catch (Throwable e) {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!", e);
    }
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Finds an initial objects factory method and its dependent classes from the
 * specified object creator class.//from  w w w.  j av  a2s  . co m
 *
 * @author paouelle
 *
 * @param  clazz the non-<code>null</code> object creator class
 * @return the initial objects factory method and its set of dependenc classes
 *         or <code>null</code> if none configured
 * @throws IllegalArgumentException if the initial objects method is not
 *         properly defined
 */
private static Pair<Method, Class<?>[]> findInitial(Class<?> clazz) {
    final InitialObjects io = clazz.getAnnotation(InitialObjects.class);

    if (io != null) {
        final String mname = io.staticMethod();

        try {
            Method m;

            try { // first look for one with a map for suffixes
                m = clazz.getMethod(mname, Map.class);
                // validate that if suffixes are defined, the method expects a Map<String, String>
                // to provide the values for the suffixes when initializing objects
                final Class<?>[] cparms = m.getParameterTypes();

                // should always be 1 as we used only 1 class in getMethod()
                if (cparms.length != 1) {
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                // should always be a map as we used a Map to find the method
                if (!Map.class.isAssignableFrom(cparms[0])) {
                    throw new IllegalArgumentException("expecting parameter for initial objects method '"
                            + mname + "' to be of type Map<String, String> in class: " + clazz.getSimpleName());
                }
                final Type[] tparms = m.getGenericParameterTypes();

                // should always be 1 as we used only 1 class in getMethod()
                if (tparms.length != 1) { // should always be 1 as it was already tested above
                    throw new IllegalArgumentException(
                            "expecting one Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
                if (tparms[0] instanceof ParameterizedType) {
                    final ParameterizedType ptype = (ParameterizedType) tparms[0];

                    // maps will always have 2 arguments
                    for (final Type atype : ptype.getActualTypeArguments()) {
                        final Class<?> aclazz = ReflectionUtils.getRawClass(atype);

                        if (String.class != aclazz) {
                            throw new IllegalArgumentException(
                                    "expecting a Map<String, String> parameter for initial objects method '"
                                            + mname + "' in class: " + clazz.getSimpleName());
                        }
                    }
                } else {
                    throw new IllegalArgumentException(
                            "expecting a Map<String, String> parameter for initial objects method '" + mname
                                    + "' in class: " + clazz.getSimpleName());
                }
            } catch (NoSuchMethodException e) { // fallback to one with no map
                m = clazz.getMethod(mname);
            }
            // validate the method is static
            if (!Modifier.isStatic(m.getModifiers())) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' is not static in class: " + clazz.getSimpleName());
            }
            // validate the return type is an array
            final Class<?> type = m.getReturnType();

            if (!type.isArray()) {
                throw new IllegalArgumentException("initial objects method '" + mname
                        + "' doesn't return an array in class: " + clazz.getSimpleName());
            }
            return Pair.of(m, io.dependsOn());
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e);
        }
    }
    return null;
}

From source file:com.rest4j.impl.MapApiTypeImpl.java

@Override
public Object cast(Object value, Type javaType) {
    if (value == null)
        return null;
    if (!(javaType instanceof ParameterizedType) || !(value instanceof Map))
        return value;
    ParameterizedType pType = (ParameterizedType) javaType;
    Type keyJavaType = pType.getActualTypeArguments()[0];
    Type elementJavaType = pType.getActualTypeArguments()[1];
    Map map = (Map) value;
    Map newMap = new LinkedHashMap();
    for (Object key : map.keySet()) {
        newMap.put(stringApiType.cast(key, keyJavaType), elementType.cast(map.get(key), elementJavaType));
    }//from  w  w w.  jav a 2s  . c  o  m
    return newMap;
}

From source file:com.google.gwt.sample.dynatablemvp.server.loc.ProxyObjectLocator.java

@SuppressWarnings("unchecked")
public ProxyObjectLocator() {
    final Type genericSuperclass2 = getClass().getGenericSuperclass();
    if (genericSuperclass2 instanceof ParameterizedType) {
        ParameterizedType genericSuperclass = (ParameterizedType) genericSuperclass2;
        final Type entityType = genericSuperclass.getActualTypeArguments()[1];
        final Type daoType = genericSuperclass.getActualTypeArguments()[2];
        HttpServletRequest request = RequestFactoryServlet.getThreadLocalRequest();
        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getSession().getServletContext());
        objectDao = (D) getTarget(context.getBean((Class<D>) daoType));
        this.keyTypeClass = (Class<K>) entityType;
    } else {/*ww w .  j  a  v a  2  s. co m*/
        this.keyTypeClass = null;
        objectDao = null;
    }
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.ConversionSchemas.java

private static Class<?> unwrapGenericSetParam(Type setType) {
    if (!(setType instanceof ParameterizedType)) {
        LOGGER.warn("Set type " + setType + " is not a " + "ParameterizedType, using default marshaler and "
                + "unmarshaler!");
        return Object.class;
    }/*from w  w  w . j ava  2  s .  c  om*/

    final ParameterizedType ptype = (ParameterizedType) setType;
    final Type[] arguments = ptype.getActualTypeArguments();

    if (arguments.length != 1) {
        LOGGER.warn("Set type " + setType + " does not have exactly one "
                + "type argument, using default marshaler and " + "unmarshaler!");
        return Object.class;
    }

    if ("byte[]".equals(arguments[0].toString())) {
        return byte[].class;
    } else {
        return (Class<?>) arguments[0];
    }
}

From source file:io.github.theangrydev.yatspeczohhakplugin.json.JsonCollectionsParameterCoercer.java

@Override
public Object coerceParameter(Type type, String stringToParse) {
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Class<?> rawType = (Class<?>) parameterizedType.getRawType();
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        return coerceParameterizedType(stringToParse, actualTypeArguments, rawType);
    } else if (type instanceof Class) {
        Class<?> targetType = ClassUtils.primitiveToWrapper((Class<?>) type);
        if (targetType.isArray()) {
            return coerceCollection(stringToParse, targetType.getComponentType(), ArrayBuilder::new);
        }/*from   ww w .  j  a  va2 s  .c o m*/
        return defaultParameterCoercer.coerceParameter(targetType, stringToParse);
    } else {
        throw new IllegalArgumentException(format("Cannot interpret '%s' as a '%s'", stringToParse, type));
    }
}

From source file:cf.spring.NatsVcapFactoryBean.java

@SuppressWarnings("unchecked")
@Override//ww w. ja va2s  .  c om
public void afterPropertiesSet() throws Exception {
    for (VcapSubscriptionConfig subscription : subscriptions) {
        final Object bean = subscription.getBean();
        final String methodName = subscription.getMethodName();
        final Method method = bean.getClass().getMethod(methodName, Publication.class);
        final ParameterizedType parameterTypes = (ParameterizedType) method.getGenericParameterTypes()[0];
        Class<MessageBody<Object>> parameterType = (Class<MessageBody<Object>>) parameterTypes
                .getActualTypeArguments()[0];
        final String queueGroup = subscription.getQueueGroup();
        cfNats.subscribe(parameterType, queueGroup, new PublicationHandler<MessageBody<Object>, Object>() {
            @Override
            public void onMessage(Publication publication) {
                try {
                    method.invoke(bean, publication);
                } catch (IllegalAccessException e) {
                    throw new Error(e);
                } catch (InvocationTargetException e) {
                    throw new NatsException(e.getTargetException());
                }
            }
        });
    }
}

From source file:eu.squadd.testing.objectspopulator.RandomValuePopulator.java

private Class<?> getGenericClass(final Field field) {
    final ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
    return (Class<?>) collectionType.getActualTypeArguments()[0];
}