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.powertac.logtool.common.DomainObjectReader.java

private Object resolveArg(Type type, String arg) throws MissingDomainObject {
    // type can be null in a few cases - nothing to be done about it?
    if (null == type) {
        return null;
    }/*from w w w . ja  v a2 s.com*/

    // check for non-parameterized types
    if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, arg);
        } else {
            return resolveSimpleArg(clazz, arg);
        }
    }

    // check for collection, denoted by leading (
    if (type instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) type;
        Class<?> clazz = (Class<?>) ptype.getRawType();
        boolean isCollection = false;
        if (clazz.equals(Collection.class))
            isCollection = true;
        else {
            Class<?>[] ifs = clazz.getInterfaces();
            for (Class<?> ifc : ifs) {
                if (ifc.equals(Collection.class)) {
                    isCollection = true;
                    break;
                }
            }
        }
        if (isCollection) {
            // expect arg to start with "("
            log.debug("processing collection " + clazz.getName());
            if (arg.charAt(0) != '(') {
                log.error("Collection arg " + arg + " does not start with paren");
                return null;
            }
            // extract element type and resolve recursively
            Type[] tas = ptype.getActualTypeArguments();
            if (1 == tas.length) {
                Class<?> argClazz = (Class<?>) tas[0];
                // create an instance of the collection
                Collection<Object> coll;
                // resolve interfaces into actual classes
                if (clazz.isInterface())
                    clazz = ifImplementors.get(clazz);
                try {
                    coll = (Collection<Object>) clazz.newInstance();
                } catch (Exception e) {
                    log.error("Exception creating collection: " + e.toString());
                    return null;
                }
                // at this point, we can split the string and resolve recursively
                String body = arg.substring(1, arg.indexOf(')'));
                String[] items = body.split(",");
                for (String item : items) {
                    coll.add(resolveSimpleArg(argClazz, item));
                }
                return coll;
            }
        }
    }

    // if we get here, no resolution
    log.error("unresolved arg: type = " + type + ", arg = " + arg);
    return null;
}

From source file:com.xwtec.xwserver.util.json.JSONArray.java

/**
 * Get the collection type from a getter or setter, or null if no type was
 * found.<br/>/*from w w w .j a v  a  2 s.co m*/
 * Contributed by [Matt Small @ WaveMaker].
 */
public static Class[] getCollectionType(PropertyDescriptor pd, boolean useGetter) throws JSONException {

    Type type;
    if (useGetter) {
        Method m = pd.getReadMethod();
        type = m.getGenericReturnType();
    } else {
        Method m = pd.getWriteMethod();
        Type[] gpts = m.getGenericParameterTypes();

        if (1 != gpts.length) {
            throw new JSONException("method " + m + " is not a standard setter");
        }
        type = gpts[0];
    }

    if (!(type instanceof ParameterizedType)) {
        return null;
        // throw new JSONException("type not instanceof ParameterizedType:
        // "+type.getClass());
    }

    ParameterizedType pType = (ParameterizedType) type;
    Type[] actualTypes = pType.getActualTypeArguments();

    Class[] ret = new Class[actualTypes.length];
    for (int i = 0; i < ret.length; i++) {
        ret[i] = (Class) actualTypes[i];
    }

    return ret;
}

From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java

/**
 * ?{@linkplain ParameterizedType}//  ww w.  jav  a  2 s .c o  m
 * @param array
 * @param type
 * @return
 * @throws ConvertException
 * @date 2012-5-14
 */
protected Object convertArrayToParameterrizedType(Object array, ParameterizedType type)
        throws ConvertException {
    Object result = null;

    Type rt = type.getRawType();
    Type[] atas = type.getActualTypeArguments();

    if (SbmUtils.isClassType(rt)) {
        Class<?> actualType = SbmUtils.narrowToClass(rt);

        //List<T>
        if (isAncestorType(List.class, actualType)) {
            result = convertArrayToList(array, actualType, atas[0]);
        }
        //Set<T>
        else if (isAncestorType(Set.class, actualType)) {
            List<?> list = convertArrayToList(array, List.class, atas[0]);
            result = listToSet(list, actualType);
        } else
            result = converterNotFoundThrow(array.getClass(), type);
    } else
        result = converterNotFoundThrow(array.getClass(), type);

    return result;
}

From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java

/**
 * ?{@linkplain ParameterizedType}/*from  w w  w  . j a  v  a 2s . c o m*/
 * @param pvm
 * @param type
 * @return
 * @throws ConvertException
 * @date 2012-5-14
 */
protected Object convertPropertyValueMapToParameterrizedType(PropertyValueMap pvm, ParameterizedType type)
        throws ConvertException {
    Object result = null;

    Type rt = type.getRawType();
    Type[] atas = type.getActualTypeArguments();

    if (SbmUtils.isClassType(rt)) {
        Class<?> actualType = SbmUtils.narrowToClass(rt);

        //List<T>
        if (isAncestorType(List.class, actualType)) {
            result = convertPropertyValueMapToList(pvm, actualType, atas[0]);
        }
        //Set<T>
        else if (isAncestorType(Set.class, actualType)) {
            List<?> tmpRe = convertPropertyValueMapToList(pvm, List.class, atas[0]);
            result = listToSet(tmpRe, actualType);
        }
        //Map<K, V>
        else if (isAncestorType(Map.class, actualType)) {
            result = convertPropertyValueMapToMap(pvm, actualType, atas[0], atas[1]);
        } else
            result = converterNotFoundThrow(pvm.getClass(), type);
    } else
        result = converterNotFoundThrow(pvm.getClass(), type);

    return result;
}

From source file:com.snaplogic.snaps.firstdata.Create.java

private ObjectSchema getSchema(SchemaProvider provider, Class<?> classType, SnapType snapType) {
    ArrayList<Method> getterMethods = findGetters(classType);
    ObjectSchema schema = null;/*from   w w w.jav a  2 s .com*/
    if (!getterMethods.isEmpty()) {
        schema = provider.createSchema(snapType, classType.getSimpleName());
    }
    String name;
    String paramType;
    Class<?> subClass;
    Class<?> fieldTypeParameterType;
    ObjectSchema subSchema;
    ParameterizedType fieldGenericType;
    for (Method method : getterMethods) {
        try {
            paramType = method.getReturnType().getName();
            if (paramType.startsWith(FD_PROXY_PKG_PREFIX) && !paramType.endsWith(TYPE)) {
                try {
                    subClass = Class.forName(paramType);
                } catch (ClassNotFoundException e) {
                    log.error(e.getMessage(), e);
                    throw new ExecutionException(e.getMessage());
                }
                subSchema = getSchema(provider, subClass, SnapType.STRING);
                if (subSchema != null) {
                    schema.addChild(subSchema);
                }
            } else if (paramType.endsWith(List.class.getSimpleName())) {
                fieldGenericType = (ParameterizedType) method.getGenericReturnType();
                fieldTypeParameterType = (Class<?>) fieldGenericType.getActualTypeArguments()[0];
                if (fieldTypeParameterType == String.class) {
                    subSchema = provider.createSchema(SnapType.COMPOSITE, getFieldName(method.getName()));
                } else {
                    subSchema = getSchema(provider, fieldTypeParameterType, SnapType.COMPOSITE);
                }
                if (subSchema != null) {
                    schema.addChild(subSchema);
                }
            } else {
                name = getFieldName(method.getName());
                schema.addChild(provider.createSchema(getDataTypes(paramType), name));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    return schema;
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings("rawtypes")
private Object getObject(Type claz, List<Type> heirarchies) throws Exception {

    ParameterizedType type = null;
    Class clas = null;/*from   w w  w  . j  a va 2  s. c  o  m*/
    if (claz instanceof ParameterizedType) {
        type = (ParameterizedType) claz;
        clas = (Class) type.getRawType();
    } else {
        clas = (Class) claz;
    }
    if (isPrimitive(clas)) {
        return getPrimitiveValue(clas);
    } else if (isMap(clas)) {
        return getMapValue(clas, type.getActualTypeArguments(), heirarchies);
    } else if (isCollection(clas)) {
        return getListSetValue(clas, type.getActualTypeArguments(), heirarchies);
    } else if (!clas.isInterface()) {
        return getObject(clas, heirarchies);
    }
    return null;
}

From source file:com.github.helenusdriver.driver.impl.ClassInfoImpl.java

/**
 * Finds an initial objects factory method for the POJO if configured.
 *
 * @author paouelle//from  w  w  w . j ava 2  s .c  o  m
 *
 * @return the initial objects factory method or <code>null</code> if none
 *         configured
 * @throws IllegalArgumentException if the initial objects method is not
 *         properly defined
 */
private Method findInitial() {
    final InitialObjects io = clazz.getAnnotation(InitialObjects.class);

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

        try {
            final Method m = (suffixesByType.isEmpty() ? clazz.getMethod(mname)
                    : clazz.getMethod(mname, Map.class));

            // 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 compatible with this class and 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());
            }
            final Class<?> ctype = type.getComponentType();

            if (!ctype.isAssignableFrom(clazz)) {
                throw new IllegalArgumentException("incompatible returned class '" + ctype.getName()
                        + "' for initial objects method '" + mname + "' in class: " + clazz.getSimpleName());
            }
            // 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();

            if (suffixesByType.isEmpty()) {
                // should always be 0 as we used no classes in getMethod()
                if (cparms.length != 0) {
                    throw new IllegalArgumentException("expecting no parameters for initial objects method '"
                            + mname + "' in class: " + clazz.getSimpleName());
                }
            } else {
                // 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());
                }
            }
            return m;
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(
                    "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e);
        }
    }
    return null;
}

From source file:org.evosuite.utils.generic.GenericClass.java

private boolean hasTypeVariables(ParameterizedType parameterType) {
    for (Type t : parameterType.getActualTypeArguments()) {
        if (t instanceof TypeVariable)
            return true;
        else if (t instanceof ParameterizedType) {
            if (hasTypeVariables((ParameterizedType) t))
                return true;
        }/*from w w w . j  a  v  a2s.  c om*/
    }

    return false;
}

From source file:org.evosuite.utils.generic.GenericClass.java

private boolean hasWildcardType(ParameterizedType parameterType) {
    for (Type t : parameterType.getActualTypeArguments()) {
        if (t instanceof WildcardType)
            return true;
        else if (t instanceof ParameterizedType) {
            if (hasWildcardType((ParameterizedType) t))
                return true;
        }/*from  ww w.j  av  a2s  . co m*/
    }

    return false;
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

/**
 * Generate schema construct for given type
 *
 * @param javaType : Class to whcih need to generate Schema
 * @return : Generated QName/*  w ww .  j av  a 2 s.co  m*/
 */
protected QName generateSchema(Class<?> javaType) throws Exception {
    String name = getClassName(javaType);
    QName schemaTypeName = typeTable.getComplexSchemaType(name);
    if (schemaTypeName == null) {
        String simpleName = getSimpleClassName(javaType);

        String packageName = getQualifiedName(javaType.getPackage());
        String targetNameSpace = resolveSchemaNamespace(packageName);

        XmlSchema xmlSchema = getXmlSchema(targetNameSpace);
        String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace);
        if (targetNamespacePrefix == null) {
            targetNamespacePrefix = generatePrefix();
            targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix);
        }

        XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        XmlSchemaComplexContentExtension complexExtension = new XmlSchemaComplexContentExtension();

        XmlSchemaElement eltOuter = new XmlSchemaElement();
        schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix);
        eltOuter.setName(simpleName);
        eltOuter.setQName(schemaTypeName);

        Class<?> sup = javaType.getSuperclass();
        if ((sup != null) && (!"java.lang.Object".equals(sup.getName()))
                && (!"java.lang.Exception".equals(sup.getName()))
                && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2")
                && !getQualifiedName(sup.getPackage()).startsWith("java.util")) {
            String superClassName = sup.getName();
            String superclassname = getSimpleClassName(sup);
            String tgtNamespace;
            String tgtNamespacepfx;
            QName qName = typeTable.getSimpleSchemaTypeName(superClassName);
            if (qName != null) {
                tgtNamespace = qName.getNamespaceURI();
                tgtNamespacepfx = qName.getPrefix();
            } else {
                tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage()));
                tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace);
                QName superClassQname = generateSchema(sup);
                if (superClassQname != null) {
                    tgtNamespacepfx = superClassQname.getPrefix();
                    tgtNamespace = superClassQname.getNamespaceURI();
                }
            }
            if (tgtNamespacepfx == null) {
                tgtNamespacepfx = generatePrefix();
                targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx);
            }
            //if the parent class package name is differ from the child
            if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().contains(tgtNamespace)) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(tgtNamespace);
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).put(generatePrefix(), tgtNamespace);
            }

            QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx);
            complexExtension.setBaseTypeName(basetype);
            complexExtension.setParticle(sequence);
            XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent();
            contentModel.setContent(complexExtension);
            complexType.setContentModel(contentModel);

        } else {
            complexType.setParticle(sequence);
        }

        complexType.setName(simpleName);

        if (Modifier.isAbstract(javaType.getModifiers())) {
            complexType.setAbstract(true);
        }

        //            xmlSchema.getItems().add(eltOuter);
        xmlSchema.getElements().add(schemaTypeName, eltOuter);
        eltOuter.setSchemaTypeName(complexType.getQName());

        xmlSchema.getItems().add(complexType);
        xmlSchema.getSchemaTypes().add(schemaTypeName, complexType);

        // adding this type to the table
        typeTable.addComplexSchema(name, eltOuter.getQName());
        // adding this type's package to the table, to support inheritance.
        typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName());

        typeTable.addClassNameForQName(eltOuter.getQName(), name);

        BeanExcludeInfo beanExcludeInfo = null;
        if (service.getExcludeInfo() != null) {
            beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType));
        }

        // we need to get properties only for this bean. hence ignore the super
        // class properties
        BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass());

        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            String propertyName = property.getName();
            if (!property.getName().equals("class") && (property.getPropertyType() != null)) {
                if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) {
                    Type genericFieldType = null;
                    try {
                        Field field = javaType.getDeclaredField(propertyName);
                        genericFieldType = field.getGenericType();
                    } catch (Exception e) {
                        //log.info(e.getMessage());
                    }

                    if (genericFieldType instanceof ParameterizedType) {
                        ParameterizedType aType = (ParameterizedType) genericFieldType;
                        Type[] fieldArgTypes = aType.getActualTypeArguments();
                        try {
                            generateSchemaforGenericFields(xmlSchema, sequence, fieldArgTypes[0], propertyName);
                        } catch (Exception e) {
                            generateSchemaforFieldsandProperties(xmlSchema, sequence,
                                    property.getPropertyType(), propertyName,
                                    property.getPropertyType().isArray());
                        }
                    } else {
                        generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(),
                                propertyName, property.getPropertyType().isArray());
                    }
                }
            }
        }
    }
    return schemaTypeName;
}