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:com.impetus.kundera.persistence.AssociationBuilder.java

/**
 * Returns associated bi-directional field.
 * /*w w w  .j av  a 2 s .  c o m*/
 * @param originalClazz
 *            Original class
 * @param referencedClass
 *            Referenced class.
 */
public Field getBiDirectionalField(Class originalClazz, Class referencedClass) {
    Field[] fields = referencedClass.getDeclaredFields();
    Class<?> clazzz = null;
    Field biDirectionalField = null;
    for (Field field : fields) {
        clazzz = field.getType();
        if (PropertyAccessorHelper.isCollection(clazzz)) {
            ParameterizedType type = (ParameterizedType) field.getGenericType();
            Type[] types = type.getActualTypeArguments();
            clazzz = (Class<?>) types[0];
        }
        if (clazzz.equals(originalClazz)) {
            biDirectionalField = field;
            break;
        }
    }

    return biDirectionalField;
}

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   www . j  a va 2  s  .  com*/
        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.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 *//* ww w  .j  a v a  2s  .com*/
private Class getClass(Class parentClass, String property, boolean element) {
    try {
        Field field = reflectionProvider.getField(parentClass, property);
        Type genericType = null;
        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }
        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter != null ? setter.getGenericParameterTypes()[0] : null;
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genericType;
            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;
            Type resultType = type.getActualTypeArguments()[index];
            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;
        }
    } catch (Exception e) {
        LOG.debug("Error while retrieving generic property class for property: {}", property, e);
    }
    return null;
}

From source file:net.larry1123.elec.util.test.config.AbstractConfigTest.java

protected void assertTest(String fieldName) throws NoSuchMethodException {
    Field field = getField(getConfigBase(), fieldName);
    Type type = field.getGenericType();
    Method method = getTestMethod(fieldName);
    method.setAccessible(true);/*  ww  w.  j  a  va 2  s . c  om*/
    try {
        method.invoke(this, fieldName, field);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:com.google.code.pathlet.web.ognl.impl.InstantiatingNullHandler.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 *//*w w  w . ja  v  a 2s . c o m*/
private Class getClass(Class parentClass, String property, boolean element) {

    try {

        Field field = reflectionProvider.getField(parentClass, property);

        Type genericType = null;

        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }

        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter.getGenericParameterTypes()[0];
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {

            ParameterizedType type = (ParameterizedType) genericType;

            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;

            Type resultType = type.getActualTypeArguments()[index];

            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;

        }
    } catch (Exception e) {
        throw new ConvertException(e);
    }
    return null;
}

From source file:com.khubla.cbean.serializer.impl.json.JSONListFieldSerializer.java

@Override
public void delete(Object o, Field field) throws SerializerException {
    final Property property = field.getAnnotation(Property.class);
    if ((null != property) && (property.cascadeDelete() == true)) {
        try {/*from   www .j av a2  s .  co  m*/
            /*
             * get the parameterized type
             */
            final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            final Class<?> containedType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
            /*
             * get cBean
             */
            final CBean<Object> cBean = CBeanServer.getInstance().getCBean(containedType);
            /*
             * get the array object
             */
            @SuppressWarnings("unchecked")
            final List<Object> list = (List<Object>) PropertyUtils.getProperty(o, field.getName());
            /*
             * iterate
             */
            for (final Object obj : list) {
                final String key = cBean.getId(obj);
                cBean.delete(new CBeanKey(key));
            }
        } catch (final Exception e) {
            throw new SerializerException(e);
        }
    }
}

From source file:info.archinnov.achilles.entity.parsing.PropertyParser.java

private <K, V> Pair<Class<K>, Class<V>> determineMapGenericTypes(Field field) {
    log.trace("Determine generic types for field Map<K,V> {} of entity class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());

    Type genericType = field.getGenericType();
    ParameterizedType pt = (ParameterizedType) genericType;
    Type[] actualTypeArguments = pt.getActualTypeArguments();

    Class<K> keyClass = propertyHelper.getClassFromType(actualTypeArguments[0]);
    Class<V> valueClass = propertyHelper.getClassFromType(actualTypeArguments[1]);

    return Pair.create(keyClass, valueClass);
}

From source file:com.facebook.stetho.json.ObjectMapper.java

private List<Object> convertArrayToList(Field field, JSONArray array)
        throws IllegalAccessException, JSONException {
    if (List.class.isAssignableFrom(field.getType())) {
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        Type[] types = parameterizedType.getActualTypeArguments();
        if (types.length != 1) {
            throw new IllegalArgumentException(
                    "Only able to handle a single type in a list " + field.getName());
        }/*ww  w  . j av a 2  s .  c om*/
        Class arrayClass = (Class) types[0];
        List<Object> objectList = new ArrayList<Object>();
        for (int i = 0; i < array.length(); ++i) {
            if (arrayClass.isEnum()) {
                objectList.add(getEnumValue(array.getString(i), arrayClass));
            } else if (canDirectlySerializeClass(arrayClass)) {
                objectList.add(array.get(i));
            } else {
                JSONObject jsonObject = array.getJSONObject(i);
                if (jsonObject == null) {
                    objectList.add(null);
                } else {
                    objectList.add(convertValue(jsonObject, arrayClass));
                }
            }
        }
        return objectList;
    } else {
        throw new IllegalArgumentException("only know how to deserialize List<?> on field " + field.getName());
    }
}

From source file:org.livespark.formmodeler.renderer.backend.service.impl.Model2FormTransformerServiceImpl.java

protected Set<FieldSetting> getClassFieldSettings(Class clazz) {
    TreeSet<FieldSetting> settings = new TreeSet<FieldSetting>();
    for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            if (annotation instanceof FieldDef) {
                FieldDef fieldDef = (FieldDef) annotation;
                Class fieldType = getFieldType(field, fieldDef);

                Class realType = fieldType;

                if (field.getGenericType() instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
                    Type paramArg = parameterizedType.getActualTypeArguments()[0];
                    realType = (Class) paramArg;
                }/*from  w w  w  .  j  a va 2s .co m*/

                FieldSetting setting = new FieldSetting(
                        field.getName(), new DefaultFieldTypeInfo(realType.getName(),
                                fieldType.isAssignableFrom(List.class), fieldType.isEnum()),
                        realType, fieldDef, field.getAnnotations());

                settings.add(setting);
            }
        }
    }
    if (clazz.getSuperclass() != null) {
        settings.addAll(getClassFieldSettings(clazz.getSuperclass()));
    }
    return settings;
}

From source file:com.fitbur.jestify.junit.spring.injector.IndexMockInjector.java

@Override
public void inject() {
    Map<DescriptorKey, ParameterDescriptor> parameterDescriptors = context.getParamaterDescriptors();
    Field field = fieldDescriptor.getField();

    Mock mock = fieldDescriptor.getMock().get();
    Integer index = mock.index();
    Optional<ParameterDescriptor> optional = parameterDescriptors.values().parallelStream()
            .filter(p -> index.equals(p.getIndex())).findFirst();

    ParameterDescriptor parameterDescriptor = optional.get();
    Parameter parameter = parameterDescriptor.getParameter();

    Type fieldType = field.getGenericType();
    Type parameterType = parameter.getParameterizedType();

    checkArgument(fieldType.equals(parameterType),
            "Can not mock field '%s'. Test class field type '%s' and class under test "
                    + "constructor parameter type '%s' at '%d' index do not match.",
            field.getName(), field.getGenericType(), parameterType, index);

    ResolvableType resolver = ResolvableType.forType(parameterType);

    Class rawType;//from  ww w  . ja  v  a  2s  .c om

    if (resolver.hasGenerics()) {
        if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
            rawType = resolver.getRawClass();
        } else {
            rawType = resolver.resolve();
        }
    } else {
        rawType = (Class) parameterType;
    }

    checkArgument(arguments[index] == null,
            "Can not mock field '%s'. Multipe test class fields have the same index of '%d'", field.getName(),
            index);

    Object instance = testReifier.reifyField(fieldDescriptor, parameterDescriptor);
    arguments[index] = instance;
}