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:com.sun.socialsite.util.DebugBeanJsonConverter.java

@SuppressWarnings("boxing")
private <T> void callSetterWithValue(T pojo, Method method, JSONObject jsonObject, String fieldName)
        throws IllegalAccessException, InvocationTargetException, NoSuchFieldException, JSONException {

    log.debug("Calling setter [" + method.getName() + "]");

    Class<?> expectedType = method.getParameterTypes()[0];
    Object value = null;/*  w  w w.  j  av  a 2 s  .c  om*/

    if (!jsonObject.has(fieldName)) {
        // Skip
    } else if (expectedType.equals(List.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type type = genericListType.getActualTypeArguments()[0];
        Class<?> rawType;
        Class<?> listElementClass;
        if (type instanceof ParameterizedType) {
            listElementClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            rawType = (Class<?>) ((ParameterizedType) type).getRawType();
        } else {
            listElementClass = (Class<?>) type;
            rawType = listElementClass;
        }

        List<Object> list = Lists.newArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray(fieldName);
        for (int i = 0; i < jsonArray.length(); i++) {
            if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(rawType)) {
                list.add(convertEnum(listElementClass, jsonArray.getJSONObject(i)));
            } else {
                list.add(convertToObject(jsonArray.getString(i), listElementClass));
            }
        }

        value = list;

    } else if (expectedType.equals(Map.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type[] types = genericListType.getActualTypeArguments();
        Class<?> valueClass = (Class<?>) types[1];

        // We only support keys being typed as Strings.
        // Nothing else really makes sense in json.
        Map<String, Object> map = Maps.newHashMap();
        JSONObject jsonMap = jsonObject.getJSONObject(fieldName);

        Iterator<?> keys = jsonMap.keys();
        while (keys.hasNext()) {
            String keyName = (String) keys.next();
            map.put(keyName, convertToObject(jsonMap.getString(keyName), valueClass));
        }

        value = map;

    } else if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(expectedType)) {
        // TODO Need to stop using Enum as a class name :(
        value = convertEnum((Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[0])
                .getActualTypeArguments()[0], jsonObject.getJSONObject(fieldName));
    } else if (expectedType.isEnum()) {
        if (jsonObject.has(fieldName)) {
            for (Object v : expectedType.getEnumConstants()) {
                if (v.toString().equals(jsonObject.getString(fieldName))) {
                    value = v;
                    break;
                }
            }
            if (value == null) {
                throw new IllegalArgumentException("No enum value  '" + jsonObject.getString(fieldName)
                        + "' in " + expectedType.getName());
            }
        }
    } else if (expectedType.equals(String.class)) {
        value = jsonObject.getString(fieldName);
    } else if (expectedType.equals(Date.class)) {
        // Use JODA ISO parsing for the conversion
        value = new DateTime(jsonObject.getString(fieldName)).toDate();
    } else if (expectedType.equals(Long.class) || expectedType.equals(Long.TYPE)) {
        value = jsonObject.getLong(fieldName);
    } else if (expectedType.equals(Integer.class) || expectedType.equals(Integer.TYPE)) {
        value = jsonObject.getInt(fieldName);
    } else if (expectedType.equals(Boolean.class) || expectedType.equals(Boolean.TYPE)) {
        value = jsonObject.getBoolean(fieldName);
    } else if (expectedType.equals(Float.class) || expectedType.equals(Float.TYPE)) {
        value = ((Double) jsonObject.getDouble(fieldName)).floatValue();
    } else if (expectedType.equals(Double.class) || expectedType.equals(Double.TYPE)) {
        value = jsonObject.getDouble(fieldName);
    } else {
        // Assume its an injected type
        value = convertToObject(jsonObject.getJSONObject(fieldName).toString(), expectedType);
    }

    if (value != null) {
        method.invoke(pojo, value);
    }
}

From source file:com.medallia.tiny.ObjectProvider.java

/**
 * Register a factory object; if this ObjectProvider is asked to
 * provide the type of object the factory produces it will
 * call {@link ObjectFactory#make()} to obtain the object.
 *//*  ww w  .j a va 2  s . c  o m*/
public <X> ObjectProvider registerFactory(ObjectFactory<X> of) {
    for (Type t : of.getClass().getGenericInterfaces()) {
        if (t instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) t;
            if (pt.getRawType().equals(ObjectFactory.class)) {
                @SuppressWarnings("unchecked")
                Class<X> x = (Class<X>) pt.getActualTypeArguments()[0];
                registerFactory(x, of);
                break;
            }
        }
    }
    return this;
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

private boolean isListString(ParameterizedType parameterizedType) {
    return List.class.equals(parameterizedType.getRawType())
            && parameterizedType.getActualTypeArguments().length == 1
            && String.class.equals(parameterizedType.getActualTypeArguments()[0]);
}

From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java

@Override
public <T> ObjectNode generateSchema(Class<T> type) throws TypeException {
    ObjectNode hyperSchema = null;/*from ww  w .  j a  v  a2 s  . c  om*/
    Annotation path = type.getAnnotation(Path.class);
    if (path != null) {
        hyperSchema = generateHyperSchemaFromResource(type);
    } else {
        ObjectNode jsonSchema = (ObjectNode) jsonSchemaGenerator.generateSchema(type);
        if (jsonSchema != null) {
            if ("array".equals(jsonSchema.get("type").asText())) {
                if (!Collection.class.isAssignableFrom(type)) {
                    ObjectNode items = (ObjectNode) jsonSchema.get("items");
                    // NOTE: Customized Iterable Class must declare the Collection object at first
                    Field field = type.getDeclaredFields()[0];
                    ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                    Class<?> genericClass = (Class<?>) genericType.getActualTypeArguments()[0];
                    ObjectNode hyperItems = transformJsonToHyperSchema(genericClass, (ObjectNode) items);
                    jsonSchema.put("items", hyperItems);
                }
                hyperSchema = jsonSchema;
            } else if (jsonSchema.has("properties")) {
                hyperSchema = transformJsonToHyperSchema(type, jsonSchema);
            } else {
                hyperSchema = jsonSchema;
            }
        }
    }

    //TODO: When available by SchemaVersion, put the $schema attribute as the correct HyperSchema ref.

    return hyperSchema;
}

From source file:org.apache.pig.EvalFunc.java

public EvalFunc() {
    // Resolve concrete type for T of EvalFunc<T>
    // 1. Build map from type param to type for class hierarchy from current class to EvalFunc
    Map<TypeVariable<?>, Type> typesByTypeVariable = new HashMap<TypeVariable<?>, Type>();
    Class<?> cls = getClass();
    Type type = cls.getGenericSuperclass();
    cls = cls.getSuperclass();/*w  w w. j av  a  2s . c o m*/
    while (EvalFunc.class.isAssignableFrom(cls)) {
        TypeVariable<? extends Class<?>>[] typeParams = cls.getTypeParameters();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] typeArgs = pType.getActualTypeArguments();
            for (int i = 0; i < typeParams.length; i++) {
                typesByTypeVariable.put(typeParams[i], typeArgs[i]);
            }
        }
        type = cls.getGenericSuperclass();
        cls = cls.getSuperclass();
    }

    // 2. Use type param to type map to determine concrete type of for T of EvalFunc<T>
    Type targetType = EvalFunc.class.getTypeParameters()[0];
    while (targetType != null && targetType instanceof TypeVariable) {
        targetType = typesByTypeVariable.get(targetType);
    }
    if (targetType == null || targetType instanceof GenericArrayType || targetType instanceof WildcardType) {
        throw new RuntimeException(String.format(
                "Failed to determine concrete type for type parameter T of EvalFunc<T> for derived class '%s'",
                getClass().getName()));
    }
    returnType = targetType;

    // Type check the initial, intermediate, and final functions
    if (this instanceof Algebraic) {
        Algebraic a = (Algebraic) this;

        String errMsg = "function of " + getClass().getName() + " is not of the expected type.";
        if (getReturnTypeFromSpec(new FuncSpec(a.getInitial())) != Tuple.class)
            throw new RuntimeException("Initial " + errMsg);
        if (getReturnTypeFromSpec(new FuncSpec(a.getIntermed())) != Tuple.class)
            throw new RuntimeException("Intermediate " + errMsg);
        if (!getReturnTypeFromSpec(new FuncSpec(a.getFinal())).equals(returnType))
            throw new RuntimeException("Final " + errMsg);
    }

}

From source file:org.openmrs.module.openhmis.commons.api.entity.impl.BaseObjectDataServiceImpl.java

/**
 * Gets a usable instance of the actual class of the generic type E defined by the implementing sub-class.
 * @return The class object for the entity.
 *//*  ww  w  . j a v  a2 s . com*/
@SuppressWarnings("unchecked")
protected Class<E> getEntityClass() {
    if (entityClass == null) {
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();

        entityClass = (Class<E>) parameterizedType.getActualTypeArguments()[0];
    }

    return entityClass;
}

From source file:org.eclipse.wb.internal.swing.databinding.model.beans.BeanSupport.java

public List<ObserveInfo> createProperties(ObserveInfo parent, IGenericType objectType) {
    try {/*from  ww w.  ja v a  2s  .c om*/
        Class<?> objectClass = objectType.getRawType();
        BeanDecorationInfo decorationInfo = DecorationUtils.getDecorationInfo(objectClass);
        IDecorationProvider decorationProvider = decorationInfo == null ? m_decorationProviderOverType
                : m_decorationProviderOverInfo;
        List<ObserveInfo> properties = Lists.newArrayList();
        // handle generic
        TypeVariable<?> superTypeParameter = null;
        Type superTypeParameterClass = null;
        if (objectClass.getTypeParameters().length == 1 && objectType.getSubTypes().size() == 1) {
            superTypeParameter = objectClass.getTypeParameters()[0];
            superTypeParameterClass = objectType.getSubTypes().get(0).getRawType();
        } else if (objectClass.getGenericSuperclass() instanceof ParameterizedType) {
            ParameterizedType superType = (ParameterizedType) objectClass.getGenericSuperclass();
            if (superType.getActualTypeArguments().length == 1
                    && superType.getActualTypeArguments()[0] instanceof Class<?>
                    && superType.getRawType() instanceof Class<?>) {
                Class<?> superClass = (Class<?>) superType.getRawType();
                if (superClass.getTypeParameters().length == 1) {
                    superTypeParameter = superClass.getTypeParameters()[0];
                    superTypeParameterClass = superType.getActualTypeArguments()[0];
                }
            }
        }
        // properties
        for (PropertyDescriptor descriptor : getLocalPropertyDescriptors(objectClass)) {
            String name = descriptor.getName();
            IGenericType propertyType = GenericUtils.getObjectType(superTypeParameter, superTypeParameterClass,
                    descriptor);
            properties.add(new BeanPropertyObserveInfo(this, parent, name, propertyType,
                    new StringReferenceProvider(name),
                    decorationProvider.getDecorator(decorationInfo, propertyType, name, descriptor)));
        }
        // Swing properties
        if (javax.swing.text.JTextComponent.class.isAssignableFrom(objectClass)) {
            replaceProperty(properties, "text",
                    new PropertiesObserveInfo(this, parent, "text", ClassGenericType.STRING_CLASS,
                            new StringReferenceProvider("text"), IObserveDecorator.BOLD,
                            new String[] { "text", "text_ON_ACTION_OR_FOCUS_LOST", "text_ON_FOCUS_LOST" }));
        } else if (javax.swing.JTable.class.isAssignableFrom(objectClass)) {
            addElementProperties(properties, parent);
            Collections.sort(properties, ObserveComparator.INSTANCE);
        } else if (javax.swing.JSlider.class.isAssignableFrom(objectClass)) {
            replaceProperty(properties, "value",
                    new PropertiesObserveInfo(this, parent, "value", ClassGenericType.INT_CLASS,
                            new StringReferenceProvider("value"), IObserveDecorator.BOLD,
                            new String[] { "value", "value_IGNORE_ADJUSTING" }));
        } else if (javax.swing.JList.class.isAssignableFrom(objectClass)) {
            addElementProperties(properties, parent);
            Collections.sort(properties, ObserveComparator.INSTANCE);
        }
        // EL property
        if (m_addELProperty && !objectClass.isPrimitive()) {
            properties.add(0, new ElPropertyObserveInfo(parent, objectType));
        }
        // Object property
        if (m_addSelfProperty && (parent == null || !(parent instanceof BeanPropertyObserveInfo))) {
            properties.add(0, new ObjectPropertyObserveInfo(objectType));
        }
        //
        return properties;
    } catch (Throwable e) {
        DesignerPlugin.log(e);
        return Collections.emptyList();
    }
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private Object createEntity(Class entity, Field[] fields, String[] nextLine) {

    Log.debug("createEntity()");

    try {//from ww  w  .  java2  s .  c om
        Object object = entity.newInstance();

        for (Field field : fields) {
            Class type = field.getType();

            // ignore Static fields
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            if (type.getSimpleName().equals("String")) {
                Integer index = fieldNames.get(field.getName());
                if (index != null) {
                    field.set(object, nextLine[index].trim());
                    Log.debug("Field name: " + field.getName() + " index[" + index + "] = " + nextLine[index]);
                }
            } else if (type.getSimpleName().equals("List")) {

                List<Object> list = new ArrayList<Object>();

                Field declaredField = object.getClass().getDeclaredField(field.getName());
                Type genericType = declaredField.getGenericType();

                if (genericType instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type[] t = pt.getActualTypeArguments();

                    // e.g. "class au.com.uptick.serendipity.server.domain.Address"
                    String className = t[0].toString().substring(6);
                    Log.debug("className: " + className);

                    Class nestedEntity = Class.forName(className);
                    Field[] nestedFields = nestedEntity.getDeclaredFields();
                    AccessibleObject.setAccessible(nestedFields, true);

                    Object nestedObject = createNestedEntity(nestedEntity, nestedFields, nextLine);

                    if (nestedObject != null) {
                        list.add(nestedObject);
                        field.set(object, list);
                    }
                }
            }
        }

        // Log.debug(object.toString());

        return object;
    } catch (Exception e) {
        Log.error("Error encountered while creating entity", e);
    }

    return null;
}

From source file:com.castlemock.web.basis.model.RepositoryImpl.java

/**
 * The default constructor for the AbstractRepositoryImpl class. The constructor will extract class instances of the
 * generic types (TYPE and ID). These instances could later be used to identify the types for when interacting
 * with the file system./*from   w  w w . j  a v  a2s .  c  o  m*/
 */
public RepositoryImpl() {
    final ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    this.dtoClass = (Class<D>) genericSuperclass.getActualTypeArguments()[1];
    this.idClass = (Class<I>) genericSuperclass.getActualTypeArguments()[2];
}

From source file:com.qihang.winter.poi.excel.export.base.ExportBase.java

/**
 * ??// w w  w. ja  v  a2  s. c  o  m
 *
 * @param exclusions
 * @param targetId
 *            ID
 * @param fields
 * @throws Exception
 */
public void getAllExcelField(String[] exclusions, String targetId, Field[] fields,
        List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> excelParams, Class<?> pojoClass,
        List<Method> getMethods) throws Exception {
    List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null;
    com.qihang.winter.poi.excel.entity.params.ExcelExportEntity excelEntity;
    // ??filed
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        // ?collection,?java,?
        if (com.qihang.winter.poi.util.PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) {
            continue;
        }
        // Excel ???
        if (field.getAnnotation(com.qihang.winter.poi.excel.annotation.Excel.class) != null) {
            excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods));
        } else if (com.qihang.winter.poi.util.PoiPublicUtil.isCollection(field.getType())) {
            com.qihang.winter.poi.excel.annotation.ExcelCollection excel = field
                    .getAnnotation(com.qihang.winter.poi.excel.annotation.ExcelCollection.class);
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> list = new ArrayList<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity>();
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    com.qihang.winter.poi.util.PoiPublicUtil.getClassFields(clz), list, clz, null);
            excelEntity = new com.qihang.winter.poi.excel.entity.params.ExcelExportEntity();
            excelEntity.setName(getExcelName(excel.name(), targetId));
            excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId));
            excelEntity
                    .setMethod(com.qihang.winter.poi.util.PoiPublicUtil.getMethod(field.getName(), pojoClass));
            excelEntity.setList(list);
            excelParams.add(excelEntity);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            newMethods.add(com.qihang.winter.poi.util.PoiPublicUtil.getMethod(field.getName(), pojoClass));
            com.qihang.winter.poi.excel.annotation.ExcelEntity excel = field
                    .getAnnotation(com.qihang.winter.poi.excel.annotation.ExcelEntity.class);
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    com.qihang.winter.poi.util.PoiPublicUtil.getClassFields(field.getType()), excelParams,
                    field.getType(), newMethods);
        }
    }
}