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:Main.java

/**
 * Returns the generic class of multi-value objects.
 * //w  ww  . j  a v  a  2 s .co m
 * @param p
 *          Field to examine
 * @return The Class<?> of generic type if any, otherwise null
 */
public static Class<?> getGenericMultivalueType(final Field p) {
    if (p.getType() instanceof Class<?>) {
        final Type genericType = p.getGenericType();
        if (genericType != null && genericType instanceof ParameterizedType) {
            final ParameterizedType pt = (ParameterizedType) genericType;
            if (pt.getActualTypeArguments() != null && pt.getActualTypeArguments().length > 0) {
                if (((Class<?>) pt.getRawType()).isAssignableFrom(Map.class)) {
                    if (pt.getActualTypeArguments()[1] instanceof Class<?>) {
                        return (Class<?>) pt.getActualTypeArguments()[1];
                    } else if (pt.getActualTypeArguments()[1] instanceof ParameterizedType)
                        return (Class<?>) ((ParameterizedType) pt.getActualTypeArguments()[1]).getRawType();
                } else if (pt.getActualTypeArguments()[0] instanceof Class<?>) {
                    return (Class<?>) pt.getActualTypeArguments()[0];
                } else if (pt.getActualTypeArguments()[0] instanceof ParameterizedType)
                    return (Class<?>) ((ParameterizedType) pt.getActualTypeArguments()[0]).getRawType();
            }
        } else if (p.getType().isArray())
            return p.getType().getComponentType();
    }
    return null;
}

From source file:org.openlegacy.utils.ReflectionUtil.java

public static Class<?> getListType(Field field) {
    try {//from   w w w.  j a va2s. c o m
        if (!(field.getGenericType() instanceof ParameterizedType)) {
            return null;
        }

        ParameterizedType type = (ParameterizedType) field.getGenericType();
        if (type.getActualTypeArguments().length == 0) {
            return null;
        }
        if (!(type.getActualTypeArguments()[0] instanceof Class)) {
            return null;
        }
        Class<?> listType = (Class<?>) type.getActualTypeArguments()[0];
        return listType;
    } catch (Exception e) {
        throw (new IllegalArgumentException(e));
    }

}

From source file:org.polymap.core.model2.engine.DefaultValues.java

/**
 * Creates a default value for the given field. The default value can be defined
 * via the {@link DefaultValue} annotation. 
 * /*ww w .ja v a2 s  .  c  om*/
 * @param field
 * @return The default value for the given field, or null if no default value was
 *         defined via {@link DefaultValue} annotation
 */
public static Object valueOf(Field field) {
    Class<?> type = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];

    // @DefaultValue
    DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
    if (defaultValue != null) {
        if (type.equals(String.class)) {
            return defaultValue.value();
        } else if (type.equals(Integer.class)) {
            return Integer.parseInt(defaultValue.value());
        }
        // XXX
        else {
            throw new UnsupportedOperationException(
                    "Default values of this type are not supported yet: " + type);
        }
    }

    // @Defaults
    Defaults defaults = field.getAnnotation(Defaults.class);
    if (defaults != null) {
        if (type.equals(String.class)) {
            return DEFAULT_STRING;
        } else if (type.equals(Integer.class)) {
            return DEFAULT_INTEGER;
        } else if (type.equals(Date.class)) {
            return DEFAULT_DATE;
        }
        // XXX
        else {
            throw new UnsupportedOperationException(
                    "Default values of this type are not supported yet: " + type);
        }
    }
    return null;
}

From source file:ReflectionUtils.java

public static Class<?> getTargetType(Field field) {
    //   Generic type, case when we have a Collection of ?
    if (field.getGenericType() instanceof ParameterizedType) {
        ParameterizedType type = (ParameterizedType) field.getGenericType();
        if (type.getActualTypeArguments().length == 1 && type.getActualTypeArguments()[0] instanceof Class)
            return (Class<?>) type.getActualTypeArguments()[0];
    }/*  www  .  java2 s.  c  o m*/

    return field.getType();
}

From source file:org.polymap.model2.engine.DefaultValues.java

/**
 * Creates a default value for the given field. The default value can be defined
 * via the {@link DefaultValue} annotation. 
 * // w w  w . ja v  a 2s . c  o  m
 * @param field
 * @return The default value for the given field, or null if no default value was
 *         defined via {@link DefaultValue} annotation
 */
public static Object valueOf(Field field) {
    Class<?> type = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];

    // @DefaultValue
    DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
    if (defaultValue != null) {
        if (type.equals(String.class)) {
            return defaultValue.value();
        } else if (type.equals(Integer.class)) {
            return Integer.parseInt(defaultValue.value());
        }
        // XXX
        else {
            throw new UnsupportedOperationException(
                    "Default values of this type are not supported yet: " + type);
        }
    }

    // @Defaults
    Defaults defaults = field.getAnnotation(Defaults.class);
    if (defaults != null) {
        if (type.equals(String.class)) {
            return DEFAULT_STRING;
        } else if (type.equals(Integer.class)) {
            return DEFAULT_INTEGER;
        } else if (type.equals(Date.class)) {
            return DEFAULT_DATE;
        } else if (type.equals(Boolean.class)) {
            return DEFAULT_BOOLEAN;
        }
        // XXX
        else {
            throw new UnsupportedOperationException(
                    "Default values of this type are not supported yet: " + type);
        }
    }
    return null;
}

From source file:ch.ifocusit.plantuml.utils.ClassUtils.java

public static Set<Class> getGenericTypes(Field field) {
    if (field.getGenericType() instanceof ParameterizedType) {
        // manage generics
        return getGenericTypes((ParameterizedType) field.getGenericType());
    }//from  w  ww.  j  av a  2 s .c om
    return new HashSet<>();
}

From source file:Main.java

public static void setField(Object object, String fieldName, Object fieldValue) {
    Class<?> objectClass = object.getClass();
    if (objectClass != null) {
        try {/*from   w  ww.ja v  a  2s.c om*/
            Field field = objectClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            Type type = field.getGenericType();

            //This is bad, but dear God I can't figure out how to convert a runtime Type to its actual type through reflection. I know how in C#....
            if (type.toString().toLowerCase().contains("short")) {
                fieldValue = Short.parseShort((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("integer")) {
                fieldValue = Integer.parseInt((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("long")) {
                fieldValue = Long.parseLong((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("boolean")) {
                fieldValue = "1".equals(fieldValue); //Java, you're the worst language. And SQLite isn't helping.
            }

            field.set(object, fieldValue);
        }

        catch (NoSuchFieldException e) {
            return;
        }

        catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:com.github.jasonruckman.sidney.core.JavaTypeRefBuilder.java

public static TypeRef buildTypeRef(Type type, TypeBindings parentBindings, Field field) {
    JavaType jt;//  ww w.j a v  a2 s  .c  o  m
    TypeBindings typeBindings;

    typeBindings = Types.binding(type, parentBindings);
    jt = Types.type(type, parentBindings);
    TypeRef ref;
    if (field == null) {
        ref = new TypeRef(jt.getRawClass());
    } else {
        Hint hint = field.getAnnotation(Hint.class);
        if (hint != null) {
            ref = new TypeRef.TypeFieldRef(hint.value(), field);
        } else {
            ref = new TypeRef.TypeFieldRef(jt.getRawClass(), field);
        }
    }

    for (Field subField : Fields.getAllFields(jt.getRawClass())) {
        Type subType = subField.getGenericType();
        TypeRef subRef = buildTypeRef(subType, typeBindings, subField);
        ref.addField((TypeRef.TypeFieldRef) subRef);
    }

    if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
        ParameterizedType t = (ParameterizedType) type;
        for (Type actualTypeArg : t.getActualTypeArguments()) {
            ref.addTypeParameter(buildTypeRef(actualTypeArg, parentBindings, null));
        }
    } else if (TypeVariable.class.isAssignableFrom(type.getClass())) {
        TypeVariable t = (TypeVariable) type;
        for (Type typeBound : t.getBounds()) {
            ref.addTypeParameter(buildTypeRef(typeBound, parentBindings, null));
        }
    } else if (GenericArrayType.class.isAssignableFrom(type.getClass())) {
        GenericArrayType t = (GenericArrayType) type;
        ref.addTypeParameter(buildTypeRef(t.getGenericComponentType(), parentBindings, null));
    }

    if (jt.isArrayType() && !GenericArrayType.class.isAssignableFrom(type.getClass())) {
        ArrayType arrType = (ArrayType) jt;
        ref.addTypeParameter(buildTypeRef(arrType.getContentType().getRawClass(), null, null));
    }

    return ref;
}

From source file:Main.java

public static void loadContext(android.content.Context context, Field field, Object object)
        throws IllegalAccessException, InvocationTargetException, InstantiationException,
        NoSuchMethodException {//  w  ww  . j  av  a 2  s  . co m
    field.setAccessible(true);
    Class fType = (Class) field.getGenericType();
    Constructor constructor = fType.getConstructor(android.content.Context.class);
    if (constructor != null) {
        field.set(object, constructor.newInstance(context));
    }
}

From source file:kina.utils.AnnotationUtils.java

/**
 * Returns the list of generic types associated to the provided field (if any).
 *
 * @param field the field instance to process.
 * @return the list of generic types associated to the provided field (if any).
 *///  w  w  w. j  a  v a 2  s.  c  o m
public static Class[] getGenericTypes(java.lang.reflect.Field field) {
    try {
        ParameterizedType type = (ParameterizedType) field.getGenericType();
        Type[] types = type.getActualTypeArguments();

        Class<?>[] res = new Class<?>[types.length];

        for (int i = 0; i < types.length; i++) {
            res[i] = (Class<?>) types[i];
        }

        return res;

    } catch (ClassCastException e) {
        return new Class<?>[] { (Class<?>) field.getGenericType() };
    }
}