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.fastmongo.odm.dbobject.mapping.core.ConverterHelper.java

/**
 * Returns an array of Type objects representing the actual type arguments of this field.
 *
 * @param field the parameterized field.
 * @return type arguments of the given field.
 *///from w ww  .ja  v a 2s  . co  m
public static Type[] getFieldGenericTypes(Field field) {
    Type[] types = GENERIC_TYPES_BY_FIELD.get(field);
    if (types == null) {
        types = ((ParameterizedType) field.getGenericType()).getActualTypeArguments();
        GENERIC_TYPES_BY_FIELD.put(field, types);
    }

    return types;
}

From source file:org.batoo.common.reflect.ReflectHelper.java

/**
 * Returns the actual generic type of a class's type parameter of the <code>member</code>.
 * <p>//w  w w.j  a va 2s .c om
 * if the <code>member</code> is a field then field's generic types are checked. Otherwise the <code>member</code> is treated a a method
 * and its return type's is checked.
 * <p>
 * 
 * @param member
 *            the member
 * @param index
 *            the index number of the generic parameter
 * @return the class of generic type
 * 
 * @param <X>
 *            the type of the class
 * 
 * @since 2.0.1
 */
@SuppressWarnings("unchecked")
public static <X> Class<X> getGenericType(Member member, int index) {
    Type type;

    if (member instanceof Field) {
        final Field field = (Field) member;
        type = field.getGenericType();

    } else {
        final Method method = (Method) member;
        type = method.getGenericReturnType();
    }

    // if not a parameterized type return null
    if (!(type instanceof ParameterizedType)) {
        return null;
    }

    final ParameterizedType parameterizedType = (ParameterizedType) type;

    final Type[] types = parameterizedType.getActualTypeArguments();

    return (Class<X>) ((types != null) && (index < types.length) ? types[index] : null);
}

From source file:com.hihframework.core.utils.ReflectUtil.java

/**
 * // w  ww .  jav  a 2 s.  c o m
 * @param obj
 * @param fieldName
 * @return
 * @author Xiaojf
 * @since 2011-9-9
 */
public static Class<?> getGenericType(Class<?> obj, String fieldName) {
    try {
        Field field = getDeclaredField(obj, fieldName);
        if (field != null) {
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            if (pt != null && pt.getActualTypeArguments() != null) {
                Type[] types = pt.getActualTypeArguments();
                if (types.length > 0) {
                    return (Class<?>) types[0];
                }
            }
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Inspects a {@link Model} class and returns all of the available and acceptable query parameter
 *   definitions, as a map of parameter names and {@link QueryParameterDescriptor} objects.
 * /*www .  jav  a 2 s .co m*/
 * @param model
 * @return
 */
public static Map<String, QueryParameterDescriptor> getAvailableQueryParameters(Class<? extends Model<?>> model,
        boolean recursive) {
    Map<String, QueryParameterDescriptor> paramMap = new HashMap<>();
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        Class<?> type = field.getType();
        if (Collection.class.isAssignableFrom(field.getType())) {
            ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            type = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
        if (field.isAnnotationPresent(Ignored.class)) {
            continue;
        } else {
            paramMap.put(fieldName,
                    new QueryParameterDescriptor(fieldName, fieldName, type, Evaluation.EQUALS));
        }
        if (field.isAnnotationPresent(ForeignKey.class)) {
            if (!recursive)
                continue;
            ForeignKey foreignKey = field.getAnnotation(ForeignKey.class);
            String relField = !"".equals(foreignKey.rel()) ? foreignKey.rel() : fieldName;
            Map<String, QueryParameterDescriptor> foreignModelMap = getAvailableQueryParameters(
                    foreignKey.model(), false);
            for (QueryParameterDescriptor descriptor : foreignModelMap.values()) {
                String newParamName = relField + "." + descriptor.getParamName();
                descriptor.setParamName(newParamName);
                paramMap.put(newParamName, descriptor);
            }
        }
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                paramMap.put(alias.value(),
                        new QueryParameterDescriptor(alias.value(),
                                alias.fieldName().equals("") ? fieldName : alias.fieldName(), type,
                                alias.evaluation()));
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            paramMap.put(alias.value(), new QueryParameterDescriptor(alias.value(),
                    alias.fieldName().equals("") ? fieldName : alias.fieldName(), type, alias.evaluation()));
        }
    }
    return paramMap;
}

From source file:de.adesso.referencer.search.helper.MyHelpMethods.java

public static String getClassNameFromListOfClasses(Field f) {
    String result = "";
    try {// w w  w.ja  v a 2s  .co  m
        ParameterizedType listType = (ParameterizedType) f.getGenericType();
        Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
        result = listClass.getName();
    } catch (Exception e) {
        result = "Error!";
        e.printStackTrace();
    }
    return result;
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 *
 * @param field/*from www  . j  ava 2s.co m*/
 * @return
 */
public static Class<?> getGenericFieldType(Field field) {
    Type fieldType = field.getGenericType();
    if (fieldType instanceof ParameterizedType) {
        Type[] t = ((ParameterizedType) fieldType).getActualTypeArguments();
        if (t != null) {
            return (Class<?>) t[0];
        }
    }
    return field.getType();
}

From source file:ca.uhn.fhir.context.ModelScanner.java

private static Class<?> getGenericCollectionTypeOfCodedField(Field next) {
    Class<?> type;/*from   w w  w .  j a v a  2 s  .com*/
    ParameterizedType collectionType = (ParameterizedType) next.getGenericType();
    Type firstArg = collectionType.getActualTypeArguments()[0];
    if (ParameterizedType.class.isAssignableFrom(firstArg.getClass())) {
        ParameterizedType pt = ((ParameterizedType) firstArg);
        firstArg = pt.getActualTypeArguments()[0];
        type = (Class<?>) firstArg;
    } else {
        type = (Class<?>) firstArg;
    }
    return type;
}

From source file:kina.utils.UtilMongoDB.java

/**
 * converts from BsonObject to an entity class with kina's anotations
 *
 * @param classEntity the entity name.//from  w w w  .j a v  a  2 s.c  om
 * @param bsonObject  the instance of the BSONObjet to convert.
 * @param <T>         return type.
 * @return the provided bsonObject converted to an instance of T.
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> T getObjectFromBson(Class<T> classEntity, BSONObject bsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    T t = classEntity.newInstance();

    Field[] fields = filterKinaFields(classEntity);

    Object insert;

    for (Field field : fields) {
        Method method = Utils.findSetter(field.getName(), classEntity, field.getType());

        Class<?> classField = field.getType();

        Object currentBson = bsonObject.get(kinaFieldName(field));
        if (currentBson != null) {

            if (Iterable.class.isAssignableFrom(classField)) {
                Type type = field.getGenericType();

                insert = subDocumentListCase(type, (List) bsonObject.get(kinaFieldName(field)));

            } else if (KinaType.class.isAssignableFrom(classField)) {
                insert = getObjectFromBson(classField, (BSONObject) bsonObject.get(kinaFieldName(field)));
            } else {
                insert = currentBson;
            }

            method.invoke(t, insert);
        }
    }

    return t;
}

From source file:org.vaadin.viritin.ListContainer.java

private static Class<?> detectTypeParameter(Class clazz, String name, int idx) throws NoSuchFieldException {
    Field declaredField = clazz.getDeclaredField(name);
    Type genericType = declaredField.getGenericType();
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        return (Class<?>) parameterizedType.getActualTypeArguments()[idx];
    }/*from w w w  . j  av  a 2s. co m*/
    return Object.class;
}

From source file:tech.sirwellington.alchemy.generator.ObjectGenerators.java

private static AlchemyGenerator<?> determineGeneratorForCollectionField(Field collectionField,
        Class<?> collectionType, Map<Class<?>, AlchemyGenerator<?>> generatorMappings) {
    if (isMapType(collectionType)) {
        return determineGeneratorForMapField(collectionField, collectionType, generatorMappings);
    }//from w ww . jav a2 s .co m

    ParameterizedType parameterizedType = (ParameterizedType) collectionField.getGenericType();
    Class<?> valueType = (Class<?>) parameterizedType.getActualTypeArguments()[0];

    AlchemyGenerator<?> generator = generatorMappings.getOrDefault(valueType,
            determineGeneratorFor(valueType, collectionField, generatorMappings));

    List<Object> list = new ArrayList<>();
    int size = one(integers(10, 100));

    for (int i = 0; i < size; ++i) {
        list.add(generator.get());
    }

    if (Set.class.isAssignableFrom(collectionType)) {
        Set set = new HashSet<>(list);
        return () -> set;
    }

    return () -> list;
}