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.conversantmedia.mapreduce.tool.annotation.handler.NamedOutputAnnotationHandler.java

/**
 * If this is a multiple output we're annotating, see if there are type parameters to
 * use for the key/value classes./*  w ww .j a v a 2 s.  c  o  m*/
 * 
 * @param target   object to reflect for type params
 * @return         the key/value type parameters
 */
protected Pair<Type, Type> getGenericTypeParams(Object target) {
    Pair<Type, Type> kvTypePair = null;
    if (target instanceof Field) {
        Field field = (Field) target;
        if (field.getType() == MultipleOutputs.class) {
            Type genericType = field.getGenericType();
            if (genericType instanceof ParameterizedType) {
                Type[] keyValueTypes = ((ParameterizedType) genericType).getActualTypeArguments();
                if (keyValueTypes != null && keyValueTypes.length == 2) {
                    kvTypePair = new ImmutablePair<>(keyValueTypes[0], keyValueTypes[1]);
                }
            }
        }
    }
    return kvTypePair;
}

From source file:org.ow2.chameleon.shell.gogo.test.converter.CollectionConverterTestCase.java

@Test
public void testConvertString() throws Exception {
    Assert.assertEquals(converterManager.convert(Integer.class, "42"), Integer.valueOf(42),
            "String to Integer");

    HashMap<Integer, String> map = new HashMap<Integer, String>();
    map.put(42, Integer.class.getName());
    Object[] in = new Object[] { map };

    Field field = CollectionConverterTestCase.class.getDeclaredField("result");
    ParameterizedType listType = (ParameterizedType) field.getGenericType();
    ReifiedType reifiedType = new GenericType(listType);

    Hashtable<Float, Class<?>> hasht = new Hashtable<Float, Class<?>>();
    hasht.put(42f, Integer.class);
    result.add(hasht);/*from  www .ja v a 2  s . c  o m*/

    Assert.assertEquals(converterManager.convert(reifiedType, in), result, "Array to List");
}

From source file:eu.squadd.testing.objectspopulator.RandomValuePopulator.java

private Class<?> getGenericClass(final Field field) {
    final ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
    return (Class<?>) collectionType.getActualTypeArguments()[0];
}

From source file:natalia.dymnikova.configuration.ConfigBeanPostProcessor.java

private void injectConfiguration(Object bean, String beanName, Field field) {
    final String path = field.getAnnotation(ConfigValue.class).value();
    try {//from w w w  .j a  v a2s.  c  o  m
        setField(field, bean, convert(field.getGenericType(), environment.config, path));
    } catch (final com.typesafe.config.ConfigException e) {
        throw unchecked(e, "Failed to apply configuration '{}' to property '{}' of bean '{}' of type {}", path,
                field.getName(), beanName, bean.getClass().getName());
    }
}

From source file:iing.uabc.edu.mx.persistencia.util.BeanManager.java

public Class getCollectionElementType(String propertyName) {
    Class elementType = null;//  w ww  .  ja v a 2s  .c om

    try {
        Field collectionField = bean.getBean().getClass().getDeclaredField(propertyName);

        ParameterizedType collectionType = (ParameterizedType) collectionField.getGenericType();

        elementType = (Class) collectionType.getActualTypeArguments()[0];

    } catch (NoSuchFieldException | SecurityException ex) {
        Logger.getLogger(BeanManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return elementType;
}

From source file:org.glassfish.hk2.utilities.test.TypeCheckerTest.java

private void getTypes() throws NoSuchFieldException {
    Class<?> clazz = getClass();
    Field field;

    field = clazz.getDeclaredField("dao");
    daoType = field.getGenericType();

    field = clazz.getDeclaredField("order");
    orderType = field.getGenericType();/*from w  w w .  j av  a  2  s. c  om*/

    field = clazz.getDeclaredField("user");
    userType = field.getGenericType();

    field = clazz.getDeclaredField("wPersistent");
    wPersistentType = field.getGenericType();

    field = clazz.getDeclaredField("wildCard");
    wildCardType = field.getGenericType();

    field = clazz.getDeclaredField("wUser");
    wUserType = field.getGenericType();
}

From source file:com.wavemaker.tools.apidocs.tools.parser.impl.ReflectionModelParser.java

protected Map<String, Property> parsePropertiesUsingFields(Class<?> classToScan) {
    Map<String, Property> properties = new LinkedHashMap<>();
    Collection<Field> fields = Collections.EMPTY_LIST;
    try {//  w ww  . j  a  va 2  s.  c om
        fields = ReflectionUtils.getFields(classToScan, NonStaticMemberPredicate.getInstance());
    } catch (Throwable th) {
        // XXX should throw? if we throw error entire swagger generation will get failed.
        // Here issues with class loader, like NoClassDefFoundError and ClassNotFound exception.
        LOGGER.error("Error while reading fields for class:{}", classToScan, th);
    }
    for (Field field : fields) {
        PropertyParser parser = new PropertyParserImpl(field.getGenericType());
        final Property property = parser.parse();
        property.setRequired(isRequired(field));
        properties.put(findFieldName(field), property);
    }
    return properties;
}

From source file:org.openehr.adl.rm.RmBeanReflector.java

private Class<?> extractGenericType(Class<?> beanClass, PropertyDescriptor pd)
        throws ReflectiveOperationException {
    checkArgument(List.class.isAssignableFrom(pd.getPropertyType()));

    Field field = getField(beanClass, pd);
    ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
    return (Class<?>) stringListType.getActualTypeArguments()[0];
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

private Class<?> getDataType(Field f) {
    if (isDynamicInnerFields(f)) {
        return (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[1];
    } else {/*  w  ww  . ja va 2 s. c  o  m*/
        return f.getType();
    }
}

From source file:com.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyCut(CutDescriptor cutDescriptor, Object[] arguments) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {//from www .  j a v a2 s  .co  m
            Cut cut = cutDescriptor.getCut();
            Field field = cutDescriptor.getField();
            Type fieldType = field.getGenericType();
            String fieldName = field.getName();

            field.setAccessible(true);

            Constructor<?> constructor = cutDescriptor.getConstructor();
            constructor.setAccessible(true);

            ResolvableType resolver = ResolvableType.forType(fieldType);

            Class rawType;

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

            Module module = testInstance.getClass().getDeclaredAnnotation(Module.class);

            GenericBeanDefinition bean = new GenericBeanDefinition();
            bean.setBeanClass(rawType);
            bean.setAutowireCandidate(false);
            bean.setScope(SCOPE_PROTOTYPE);
            bean.setPrimary(true);
            bean.setLazyInit(true);
            bean.setRole(RootBeanDefinition.ROLE_APPLICATION);
            bean.setAutowireMode(RootBeanDefinition.AUTOWIRE_NO);
            appContext.registerBeanDefinition(fieldName, bean);
            if (module != null) {
                appContext.register(module.value());
            }
            appContext.refresh();

            Object instance = appContext.getBean(fieldName, arguments);

            if (cut.value()) {
                instance = spy(instance);
            }

            field.set(testInstance, instance);

            return instance;
        } catch (SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    });
}