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:tech.sirwellington.alchemy.generator.ObjectGenerators.java

private static boolean lacksGenericTypeArguments(Field field) {
    Type genericType = field.getGenericType();

    return !(genericType instanceof ParameterizedType);
}

From source file:org.synku4j.wbxml.util.WbxmlUtil.java

/**
 * Introspect the given class, extracting all the codepage information, populating the supplied collection.
 * /*from  w  w w .  j  a  v  a2s .  co  m*/
 * @param clazz to introspect.
 * @param pages to populate.
 */
public static void introspect(final Class<?> clazz, final Collection<WbxmlCodePage> pages) {
    final WbxmlPage page = clazz.getAnnotation(WbxmlPage.class);
    if (page == null) {
        // no page means we skip it.
        return;
    }

    if (page.index() == -1) {
        return;
    }

    WbxmlField root = clazz.getAnnotation(WbxmlField.class);
    WbxmlCodePageWrapper codePage = null;
    // TODO : For the introspect use a Map, then collate to collection
    for (WbxmlCodePage cp : pages) {
        if (cp.getIndex() == page.index()) {
            codePage = (WbxmlCodePageWrapper) cp;
            break;
        }
    }

    if (codePage == null) {
        codePage = new WbxmlCodePageWrapper(page);
        pages.add(codePage);
    }

    if (root != null) {
        codePage.addCodePageField(new WbxmlCodePageFieldWrapper(page, root, clazz));
    }

    // Parse from the root down
    for (Field field : WbxmlUtil.getFields(clazz)) {
        final WbxmlField wbxmlField = field.getAnnotation(WbxmlField.class);
        final Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            Type rawType = ptype.getRawType();

            if (Collection.class.isAssignableFrom((Class<?>) rawType)) {
                Type[] args = ptype.getActualTypeArguments();
                if (args != null && args.length > 0) {
                    for (Type arg : args) {
                        if (arg instanceof Class<?>) {
                            introspect((Class<?>) arg, pages);
                        }
                    }
                }
            }
        } else if (type instanceof Class<?>) {
            introspect((Class<?>) type, pages);
        }

        // if the class has a page, add it to the codepage.
        Class<?> modelClass = null;
        if (type instanceof Class<?>) {
            if (((Class<?>) type).getAnnotation(WbxmlPage.class) != null) {
                modelClass = (Class<?>) type;
            }
        }

        codePage.addCodePageField(new WbxmlCodePageFieldWrapper(page, wbxmlField, modelClass));
    }
}

From source file:com.oltpbenchmark.util.ClassUtil.java

/**
 * Get the generic types for the given field
 * @param field/*from  ww w.  ja  v a 2 s .  c o m*/
 * @return
 */
public static List<Class<?>> getGenericTypes(Field field) {
    ArrayList<Class<?>> generic_classes = new ArrayList<Class<?>>();
    Type gtype = field.getGenericType();
    if (gtype instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) gtype;
        getGenericTypesImpl(ptype, generic_classes);
    }
    return (generic_classes);
}

From source file:com.ghy.common.util.reflection.ReflectionUtils.java

/**
 * ?string//  ww  w.  java2 s  . c  o  m
 * @param object
 * @param map
 * @throws Exception 
 * @throws NoSuchMethodException 
 * @throws SecurityException 
 */
public static void fromObtoMap(Object object, Map<String, String> map)
        throws SecurityException, NoSuchMethodException, Exception {
    if (object != null) {//if (object!=null )  ----begin
        // 
        Class<?> clz = object.getClass();
        // ?Field
        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {// --for() begin
            // String
            if (field.getGenericType().toString().equals("class java.lang.String")) { // type???"class "????
                // gettet
                String methodName = field.getName();
                Method m = (Method) object.getClass().getMethod("get" + getMethodName(methodName));
                String val = (String) m.invoke(object);// getter?
                if (val != null) {
                    map.put(methodName, val);
                }
            }
        }
    }
}

From source file:org.eclipse.smarthome.core.types.util.UnitUtils.java

/**
 * The name of the dimension as stated in the ChannelType configuration.
 * e.g.// w w w  . java2s  .  c o m
 * <p>
 * <code> Unit: 'm' -> "Length"</code>
 * <p>
 * <code> Unit: 'kWh' -> "Energy"</code>
 * <p>
 * If the {@link Unit} can not be found in any of the available Measurement systems, it returns <code>null</code>
 *
 * @param unit The {@link Unit} to get the Dimension's name from.
 * @return The Dimension string or null if the unit can not be found in any of the SystemOfUnits.
 */
public static @Nullable String getDimensionName(Unit<?> unit) {
    for (Class<? extends SystemOfUnits> system : ALL_SYSTEM_OF_UNITS) {
        for (Field field : system.getDeclaredFields()) {
            if (field.getType().isAssignableFrom(Unit.class) && Modifier.isStatic(field.getModifiers())) {

                Type genericType = field.getGenericType();
                if (genericType instanceof ParameterizedType) {
                    String dimension = ((Class<?>) ((ParameterizedType) genericType)
                            .getActualTypeArguments()[0]).getSimpleName();
                    Unit<?> systemUnit;
                    try {
                        systemUnit = (Unit<?>) field.get(null);
                        if (systemUnit == null) {
                            LOGGER.warn("Unit field points to a null value: {}", field);
                        } else if (systemUnit.isCompatible(unit)) {
                            return dimension;
                        }
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        LOGGER.error("The unit field '{}' seems to be not accessible", field, e);
                    }
                } else {
                    LOGGER.warn("There is a unit field defined which has no generic type parametrization: {}",
                            field);
                }
            }
        }
    }
    return null;
}

From source file:org.apache.pulsar.common.util.FieldParser.java

/**
 * Converts value as per appropriate DataType of the field.
 *
 * @param strValue/*from   www  .  ja va  2s.c o  m*/
 *            : string value of the object
 * @param field
 *            : field of the attribute
 * @return
 */
public static Object value(String strValue, Field field) {
    checkNotNull(field);
    // if field is not primitive type
    if (field.getGenericType() instanceof ParameterizedType) {
        Class<?> clazz = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
        // convert to list
        if (field.getType().equals(List.class))
            return stringToList(strValue, clazz);
        // convert to set
        else if (field.getType().equals(Set.class))
            return stringToSet(strValue, clazz);
        else
            throw new IllegalArgumentException(
                    format("unsupported field-type %s for %s", field.getType(), field.getName()));
    } else {
        return convert(strValue, field.getType());
    }
}

From source file:io.neba.core.util.ReflectionUtil.java

/**
 * Resolves the generic type of a {@link Collection} from a {@link Field}, e.g.
 *
 * <pre>/*  w w w .  j  a  va 2 s . c  o m*/
 * private List&lt;MyModel&gt; myModel -&gt; MyModel.
 * </pre>
 *
 * @param field must not be <code>null</code>.
 * @return never null.
 */
public static Class<?> getCollectionComponentType(Class<?> definingType, Field field) {
    if (field == null) {
        throw new IllegalArgumentException("Method parameter field must not be null.");
    }

    // The generic type may contain the generic type declarations, e.g. List<String>.
    Type type = field.getGenericType();
    if (!(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException("Cannot obtain the component type of " + field
                + ", it does not declare generic type parameters.");
    }

    // Only the ParametrizedType contains reflection information about the actual type.
    ParameterizedType parameterizedType = (ParameterizedType) type;

    Type[] typeArguments = parameterizedType.getActualTypeArguments();

    // We expect exactly one argument representing the model type.
    if (typeArguments.length != 1) {
        signalUnsupportedNumberOfTypeDeclarations(field);
    }

    Type componentType = typeArguments[0];

    // Wildcard type <X ... Y>
    if (componentType instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) componentType;
        Type[] lowerBounds = wildcardType.getLowerBounds();
        if (lowerBounds.length == 0) {
            throw new IllegalArgumentException("Cannot obtain the component type of " + field
                    + ", it has a wildcard declaration with an upper"
                    + " bound (<? extends Y>) and is thus read-only."
                    + " Only simple type parameters (e.g. List<MyType>)"
                    + " or lower bound wildcards (e.g. List<? super MyModel>)" + " are supported.");
        }
        componentType = lowerBounds[0];
    }

    return getRawType(componentType, definingType);
}

From source file:utils.ReflectionService.java

public static Map createClassModel(Class clazz, int maxDeep) {
    Map map = new HashMap();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);/*from  ww w  .  j  av a  2  s  . co  m*/
        String key = field.getName();
        try {
            Class<?> type;
            if (Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                type = (Class<?>) collectionType.getActualTypeArguments()[0];
            } else {
                type = field.getType();
            }

            //            System.out.println(key + " ReflectionResource.createClassModel ==== putting type: " + field.getType().getName() + ", static: "
            //            + Modifier.isStatic(field.getModifiers()) + ", enum: " + type.isEnum() + ", java.*: " + type.getName().startsWith("java"));

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            } else if (type.isEnum()) {
                map.put(key, Enum.class.getName());
            } else if (!type.getName().startsWith("java") && !key.startsWith("_") && maxDeep > 0) {
                map.put(key, createClassModel(type, maxDeep - 1));
            } else {
                map.put(key, type.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return map;
}

From source file:org.jiemamy.utils.reflect.ReflectionUtil.java

/**
 * ?????????/*from  w  ww  .ja va 2s  . c o  m*/
 * 
 * @param field 
 * @return ??????? 
 * @throws IllegalArgumentException ?{@code null}???
 */
public static Class<?> getElementTypeOfCollectionFromFieldType(Field field) {
    Validate.notNull(field);
    Type type = field.getGenericType();
    return getElementTypeOfCollection(type);
}

From source file:org.jiemamy.utils.reflect.ReflectionUtil.java

/**
 * ?????????//from  w  w w  .jav a 2s  .co  m
 * 
 * @param field 
 * @return ???????
 * @throws IllegalArgumentException ?{@code null}???
 */
public static Class<?> getElementTypeOfListFromFieldType(Field field) {
    Validate.notNull(field);
    Type type = field.getGenericType();
    return getElementTypeOfList(type);
}