Example usage for java.lang.reflect Field getGenericType

List of usage examples for java.lang.reflect Field getGenericType

Introduction

In this page you can find the example usage for java.lang.reflect Field getGenericType.

Prototype

public Type getGenericType() 

Source Link

Document

Returns a Type object that represents the declared type for the field represented by this Field object.

Usage

From source file:org.eiichiro.bootleg.AbstractRequest.java

/**
 * Constructs the value of Web endpoint parameter.
 * Web endpoint parameter declaration falls into the several patterns and 
 * each pattern has the own construction logic as below: 
 * <ol>/*from  w  w  w  . j a va  2  s . c  o  m*/
 * <li>Named array type - Unsupported. Always returns <code>null</code>.</li>
 * <li>Named collection of core value type - Supported. The collection 
 * instance is constructed according to the default implementation type 
 * (See {@code Types#getDefaultImplementationType(Type)}). If the collection 
 * type is not supported (See {@code Types#isSupportedCollection(Type)}), 
 * this method returns <code>null</code>. Each of the collection elements is 
 * constructed from the values that {@code values} has returned as the same 
 * way of the following core value type. If the constructed collection has 
 * no element, this method returns <code>null</code>.</li>
 * <li>Named collection of user-defined value type - Supported. The 
 * collection instance is constructed according to the default 
 * implementation type (as the same as collection of core value type). Each 
 * of the collection elements is constructed from the values that 
 * {@code values} has returned as the same way of following user-defined 
 * value type.
 * </li>
 * <li>Named collection of user-defined object type - Unsupported. Always 
 * returns <code>null</code>.</li>
 * <li>Named core value type - Supported. The value that {@code value} has 
 * returned is converted to the core value type. If the conversion 
 * failed, returns <code>null</code></li>
 * <li>Named user-defined value type - Supported. If the value that 
 * {@code value} has returned is assignable to the user-defined value type, 
 * returns it. If the value that {@code value} has returned is 
 * {@code String.class}, this method constructs the user-defined value type 
 * with public constructor that takes one String.class parameter or public 
 * static <code>valueOf(String.class)</code> method. If the conversion 
 * failed, returns <code>null</code>.
 * </li>
 * <li>Named user-defined object type - Partially supported. If the value 
 * that {@code value} method has returned is assignable to the user-defined 
 * object type, returns it. Otherwise, returns <code>null</code> (does not 
 * any type conversion). </li>
 * <li>Not named array type - Unsupported. Always returns <code>null</code>.
 * </li>
 * <li>Not named collection of core value type - Unsupported. Always returns 
 * <code>null</code>.</li>
 * <li>Not named collection of user-defined value type - Unsupported. Always 
 * returns <code>null</code>.</li>
 * <li>Not named collection of user-defined object type - Unsupported. 
 * Always returns <code>null</code>.</li>
 * <li>Not named core value type - Unsupported. Always returns 
 * <code>null</code>.</li>
 * <li>Not named user-defined value type - Unsupported. Always returns 
 * <code>null</code>.</li>
 * <li>Not named user-defined object type - Supported. First, this method 
 * instantiates the user-defined object instance form public default 
 * constructor, and then constructs each of the instances' fields value 
 * according to the named type construction described above (by invoking 
 * {@code #newParameter(WebContext, Type, String)} with the field 
 * type and field name). If the instantiation is failed, returns <code>null
 * </code>.
 * </li>
 * </ol>
 * This method is overridable. You can provide your own value construction 
 * to Web endpoint parameter by overriding this method.
 * 
 * @param type The parameter type.
 * @param name The parameter name.
 * @param value The {@code Function} that returns the value corresponding to 
 * the specified name from its own source.
 * The returned value is converted to appropriate parameter type.
 * @param values The {@code Function} that returns the value corresponding 
 * to the specified name from its own source, as {@code Collection} view.
 * @return The value of Web endpoint parameter.
 */
@SuppressWarnings("unchecked")
protected Object parameter(Type type, String name, Function<String, Object> value,
        Function<String, Collection<Object>> values) {
    if (name != null && !name.isEmpty()) {
        // Named parameter construction.
        if (Types.isArray(type)) {
            // Named array type.
            logger.debug("Array type [" + type + "] is not supported in [" + getClass() + "]");
        } else if (Types.isCollection(type)) {
            // Named collection type.
            if (Types.isSupportedCollection(type)) {
                Collection<Object> objects = values.apply(name);

                if (objects == null) {
                    logger.debug("Collection named [" + name + "] not found");
                } else {
                    Class<?> elementType = Types.getElementType(type);
                    boolean coreValueType = Types.isCoreValueType(elementType);

                    if (!coreValueType && !Types.isUserDefinedValueType(elementType)) {
                        // Named collection of user-defined object.
                        logger.debug("Collection element type [" + elementType + "] is not supported in ["
                                + getClass() + "]");
                    } else {
                        try {
                            Class<?> implementationType = Types.getDefaultImplementationType(type);
                            Collection<Object> collection = (Collection<Object>) implementationType
                                    .newInstance();

                            for (Object object : objects) {
                                // Named collection of core value type.
                                // Named collection of user-defined value type.
                                Object convert = (coreValueType) ? convert(object, elementType)
                                        : convertUserDefinedValueType(object, elementType);

                                if (convert != null && ClassUtils.primitiveToWrapper(elementType)
                                        .isAssignableFrom(convert.getClass())) {
                                    collection.add(convert);
                                } else {
                                    logger.debug("Parameter [" + convert + "] cannot be converted to ["
                                            + elementType + "]");
                                }
                            }

                            return (!collection.isEmpty()) ? collection : null;
                        } catch (Exception e) {
                            logger.debug("Cannot instantiate [" + Types.getDefaultImplementationType(type)
                                    + "] (Default implementation type of [" + type + "])", e);
                        }
                    }
                }

            } else {
                logger.debug("Parameter type [" + type + "] is not supported in [" + getClass() + "]");
            }

        } else if (Types.isCoreValueType(type)) {
            // Named core value type.
            Class<?> rawType = Types.getRawType(type);
            Object object = value.apply(name);

            if (object == null) {
                logger.debug("Value named [" + name + "] not found");
            } else {
                Object convert = convert(object, rawType);

                if (convert != null
                        && ClassUtils.primitiveToWrapper(rawType).isAssignableFrom(convert.getClass())) {
                    return convert;
                } else {
                    logger.warn("Parameter [" + convert + "] cannot be converted to [" + type + "]");
                }
            }

        } else if (Types.isUserDefinedValueType(type)) {
            // Named user-defined value type.
            Object object = value.apply(name);
            Class<?> rawType = Types.getRawType(type);

            if (object == null) {
                logger.debug("Value named [" + name + "] not found");
            } else {
                Object userDefinedValueType = convertUserDefinedValueType(object, rawType);

                if (userDefinedValueType == null) {
                    logger.warn("Parameter [" + object + "] cannot be converted to [" + type + "]");
                }

                return userDefinedValueType;
            }

        } else {
            // Named user-defined object type.
            Object object = value.apply(name);

            if (object == null) {
                logger.debug("Value named [" + name + "] not found");
            } else if (Types.getRawType(type).isAssignableFrom(object.getClass())) {
                return object;
            } else {
                logger.warn("Parameter [" + object + "] cannot be converted to [" + type + "]");
            }
        }

    } else {
        // Non-named parameter construction.
        if (Types.isArray(type) || Types.isCollection(type) || Types.isCoreValueType(type)
                || Types.isUserDefinedValueType(type)) {
            // Not named array type.
            // Not named collection (of core value type or user-defined object type).
            // Not named core value type.
            // Not named user-defined value type.
            logger.debug("Non-named parameter type [" + type + "] is not supported in [" + getClass() + "]");
        } else {
            // Not named user-defined object type.
            Class<?> rawType = Types.getRawType(type);

            try {
                Object instance = rawType.newInstance();

                for (Field field : rawType.getDeclaredFields()) {
                    Object object = parameter(field.getGenericType(), field.getName(), value, values);

                    if (object != null) {
                        field.setAccessible(true);
                        field.set(instance, object);
                    }
                }

                return instance;
            } catch (Exception e) {
                logger.warn("Cannot instantiate [" + type + "]", e);
            }
        }
    }

    return null;
}

From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java

/**
 * Converts a model property to a SwaggerModelProperty in the event that it is a collection type.
 *
 * @param property      The model property to convert.
 * @param models        The hashmap of models that are being documented so that they can be referenced by swagger-ui.
 * @param modelProperty The SwaggerModelProperty to convert this property into.
 * @return The converted SwaggerModelProperty.
 *//*  ww w  .j  av  a 2s.  co m*/
private SwaggerModelProperty handleCollectionType(Field property, HashMap<String, SwaggerModel> models,
        SwaggerModelProperty modelProperty) {
    String type = property.getType().getSimpleName();
    if (COLLECTION_TYPES.contains(type)) {
        ParameterizedType parameterizedType = (ParameterizedType) property.getGenericType();
        Type[] genericTypes = parameterizedType.getActualTypeArguments();
        if (genericTypes.length > 0) {
            // Swagger UI doesn't support the fact that a Parameter could be a collection/generic that
            // references two classes, such as HashMap<Class1, Class2>. If it did, then we wouldn't limit this method to
            // just COLLECTION_TYPES.
            Class genericClass = (Class) genericTypes[0];
            addModel(models, genericClass);
            HashMap<String, String> items = new HashMap<>();
            if (PRIMITIVE_TYPES.contains(genericClass.getSimpleName())) {
                items.put("type", genericClass.getSimpleName());
            } else {
                items.put(REFERENCE_TYPE, genericClass.getSimpleName());
            }
            modelProperty.setItems(items);
        }
    }
    return modelProperty;
}

From source file:com.qihang.winter.poi.excel.imports.base.ImportBaseService.java

/**
 * ??/*from   w  ww.  j  a  v a 2  s .  c o  m*/
 * 
 * 
 * @param exclusions
 * @param targetId
 *            ID
 * @param fields
 * @param excelCollection
 * @throws Exception
 */
public void getAllExcelField(String targetId, Field[] fields, Map<String, ExcelImportEntity> excelParams,
        List<com.qihang.winter.poi.excel.entity.params.ExcelCollectionParams> excelCollection,
        Class<?> pojoClass, List<Method> getMethods) throws Exception {
    ExcelImportEntity excelEntity = null;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (PoiPublicUtil.isNotUserExcelUserThis(null, field, targetId)) {
            continue;
        }
        if (PoiPublicUtil.isCollection(field.getType())) {
            // ?
            com.qihang.winter.poi.excel.entity.params.ExcelCollectionParams collection = new com.qihang.winter.poi.excel.entity.params.ExcelCollectionParams();
            collection.setName(field.getName());
            Map<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>();
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            collection.setType(clz);
            getExcelFieldList(targetId, PoiPublicUtil.getClassFields(clz), clz, temp, null);
            collection.setExcelParams(temp);
            collection.setExcelName(field.getAnnotation(ExcelCollection.class).name());
            additionalCollectionName(collection);
            excelCollection.add(collection);
        } else if (PoiPublicUtil.isJavaClass(field)) {
            addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, excelParams);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            newMethods.add(PoiPublicUtil.getMethod(field.getName(), pojoClass));
            getAllExcelField(targetId, PoiPublicUtil.getClassFields(field.getType()), excelParams,
                    excelCollection, field.getType(), newMethods);
        }
    }
}

From source file:uk.ac.susx.tag.method51.core.params.Params.java

@PostConstruct
void init() {// w  ww  .  ja v a 2  s  .com
    codec = new ParamsCodec(getClass());
    try {
        Field paramFieldField = Param.class.getDeclaredField("field");
        Field paramFinalizedField = Param.class.getDeclaredField("finalized");
        Field paramTypeField = Param.class.getDeclaredField("type");
        paramFieldField.setAccessible(true);
        paramTypeField.setAccessible(true);
        paramFinalizedField.setAccessible(true);

        for (Field f : getAllParamFields(this.getClass())) {
            f.setAccessible(true);
            Param p = (Param) f.get(this);
            if (p == null) {
                throw new RuntimeException("Params Param fields must be non-null");
            } else {
                paramFieldField.set(p, f);
                if (paramTypeField.get(p) == null) {
                    paramTypeField.set(p, ParamsRegistry.inferParamType(
                            ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0]));
                }
                paramFinalizedField.set(p, true);
            }

            fields.put(f.getName(), p);
        }
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("no field field on param object? wut??");
    } catch (IllegalAccessException e) {
        LOG.error("", e);
    }
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected Class getFieldType(Field field) {
    Type genericType = field.getGenericType();
    Class type;/*from   w ww.  j av a2 s  .  c  o  m*/
    if (genericType instanceof ParameterizedType) {
        Type[] types = ((ParameterizedType) genericType).getActualTypeArguments();
        if (Map.class.isAssignableFrom(field.getType()))
            type = (Class<?>) types[1];
        else
            type = (Class<?>) types[0];
    } else {
        type = getFieldTypeAccordingAnnotations(field);
    }
    if (type == null)
        throw new IllegalArgumentException("Field " + field
                + " must either be of parametrized type or have a JPA annotation declaring a targetEntity");
    return type;
}

From source file:org.tinygroup.tinyioc.impl.BeanContainerImpl.java

private <T> void buildObject(T object, Class<T> clazz) {
    for (Field field : clazz.getDeclaredFields()) {
        Inject inject = field.getAnnotation(Inject.class);
        ////w  w w  .j av  a 2  s . c  o  m
        if (inject != null) {
            //                String name = null;
            Named named = field.getAnnotation(Named.class);
            Value valueAnnotation = field.getAnnotation(Value.class);
            if (named != null && named.value().length() > 0) {
                //                    name = named.value();
            }
            Object value = null;
            Type fc = field.getGenericType();
            if (fc instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) fc;
                Class genericClazz = (Class) pt.getActualTypeArguments()[0];
                value = getCollectionObject(field, genericClazz);
            } else if (valueAnnotation != null && valueAnnotation.value().length() > 0) {
                //
                value = getValueObject(field, valueAnnotation.value());
            } else {
                value = getSingleObject(field, inject, named);

            }
            if (value != null) {
                try {
                    BeanUtils.setProperty(object, field.getName(), value);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException(String.format("%s%sBean?!",
                        object.getClass().getName(), field.getName()));
            }
        }
    }
}

From source file:com.threewks.thundr.search.gae.meta.SearchMetadata.java

private void findFieldAccessors(Class<T> type) {
    for (Field field : ReflectUtil.getSupportedFields(type)) {
        if (field.isAnnotationPresent(SearchId.class)) {
            String name = determineName(field);
            String encodedName = encodeFieldName(name);
            idAccessor = new FieldAccessor<T, K>(type, field, name, encodedName, IndexType.Identifier);
            encodedFieldNames.put(encodedName, name);
            accessors.put(name, idAccessor);
        }//from   w  w  w . java 2 s. c  om
        if (field.isAnnotationPresent(SearchIndex.class)) {
            String name = determineName(field);
            String encodedNamed = encodeFieldName(name);
            IndexType indexType = field.getAnnotation(SearchIndex.class).as();
            if (indexType == IndexType.Automatic) {
                indexType = indexTypeLookup.inferIndexType(field.getGenericType());
            }
            accessors.put(name, new FieldAccessor<T, Object>(type, field, name, encodedNamed, indexType));
            encodedFieldNames.put(encodedNamed, name);
        }
    }
}

From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java

public void populate(MBT mbt, NBTTagCompound nbt, Object o) {
    Class clazz = o.getClass();// w  w w.j  a  va  2s  . c  o  m
    try {
        while (clazz != null && clazz != Object.class) {
            if (!clazz.isAnnotationPresent(MBTIgnore.class)) {
                for (Field field : clazz.getDeclaredFields()) {
                    if (!field.isAnnotationPresent(MBTIgnore.class)) {
                        field.setAccessible(true);
                        if (nbt.hasKey(field.getName())) {
                            if (encodeStatic || !Modifier.isStatic(field.getModifiers())) {
                                if (Modifier.isFinal(field.getModifiers())) {
                                    if (encodeFinal) {
                                        Field modifiers = Field.class.getDeclaredField("modifiers");
                                        modifiers.setAccessible(true);
                                        modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);

                                        if (field.getGenericType() instanceof ParameterizedType) {
                                            Type[] types = ((ParameterizedType) field.getGenericType())
                                                    .getActualTypeArguments();
                                            Class[] clas = new Class[] {};
                                            for (Type type : types) {
                                                if (type instanceof Class) {
                                                    clas = ArrayUtils.add(clas, (Class) type);
                                                }
                                            }
                                            field.set(o, mbt.fromNBT(nbt.getTag(field.getName()),
                                                    field.getType(), clas));
                                        } else {
                                            field.set(o,
                                                    mbt.fromNBT(nbt.getTag(field.getName()), field.getType()));
                                        }
                                    }
                                } else {
                                    if (field.getGenericType() instanceof ParameterizedType) {
                                        Type[] types = ((ParameterizedType) field.getGenericType())
                                                .getActualTypeArguments();
                                        Class[] clas = new Class[] {};
                                        for (Type type : types) {
                                            if (type instanceof Class) {
                                                clas = ArrayUtils.add(clas, (Class) type);
                                            }
                                        }
                                        field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(),
                                                clas));
                                    } else {
                                        field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            clazz = encodeSuper ? clazz.getSuperclass() : Object.class;
        }
    } catch (IllegalArgumentException e) {
        Throwables.propagate(e);
    } catch (IllegalAccessException e) {
        Throwables.propagate(e);
    } catch (NoSuchFieldException e) {
        Throwables.propagate(e);
    } catch (SecurityException e) {
        Throwables.propagate(e);
    }
}

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

private <E> Class<E> getCollectionGenericType(Field f) {
    //since this is an iterable we actually need the generic type of the iterable
    //see http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list 
    Type type = f.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType paramType = (ParameterizedType) type;
        return paramType.getActualTypeArguments().length > 0 ? (Class<E>) paramType.getActualTypeArguments()[0]
                : null;/*from   ww  w. j  a  v  a 2s.c o m*/
    } else if (type instanceof Class) {
        return (Class) type;
    } else {
        Log.error("cannot determine type of " + type.getTypeName());
        return null;
    }
}

From source file:cn.bzvs.excel.export.base.ExportBase.java

/**
 * ??/*from   w  w w .  j av a 2 s .c om*/
 *
 * @param exclusions
 * @param targetId   ID
 * @param fields
 * @throws Exception
 */
public void getAllExcelField(String[] exclusions, String targetId, Field[] fields,
        List<ExcelExportEntity> excelParams, Class<?> pojoClass, List<Method> getMethods) throws Exception {
    List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null;
    ExcelExportEntity excelEntity;
    // ??filed
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        // ?collection,?java,?
        if (PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) {
            continue;
        }
        // Excel ???
        if (field.getAnnotation(Excel.class) != null) {
            excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods));
        } else if (PoiPublicUtil.isCollection(field.getType())) {
            ExcelCollection excel = field.getAnnotation(ExcelCollection.class);
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            List<ExcelExportEntity> list = new ArrayList<ExcelExportEntity>();
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(clz), list, clz, null);
            excelEntity = new ExcelExportEntity();
            excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, null));
            excelEntity.setOrderNum(
                    Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0")));
            excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            excelEntity.setList(list);
            excelParams.add(excelEntity);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            ExcelEntity excel = field.getAnnotation(ExcelEntity.class);
            getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods);
        }
    }
}