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.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyField(FieldDescriptor fieldDescriptor, ParameterDescriptor parameterDescriptor) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {/*from   ww w.  j ava 2 s.com*/
            Object instance;
            Field field = fieldDescriptor.getField();
            Type fieldType = field.getGenericType();
            field.setAccessible(true);

            Optional<Mock> optMock = fieldDescriptor.getMock();
            if (optMock.isPresent()) {
                Mock mock = optMock.get();
                Object value = field.get(testInstance);
                //if the field value is set then create a mock otherwise create a mock
                //that delegates to the value
                if (value == null) {
                    MockSettings settings = withSettings().defaultAnswer(mock.answer());

                    if (mock.extraInterfaces().length > 0) {
                        settings.extraInterfaces(mock.extraInterfaces());

                    }

                    instance = mock(field.getType(), settings);
                } else {
                    instance = mock(field.getType(), delegatesTo(value));
                }

            } else {
                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 = (Class) fieldType;
                }

                instance = appContext.getBean(rawType);
            }

            field.set(testInstance, instance);
            fieldDescriptor.setInstance(instance);
            parameterDescriptor.setInstance(instance);

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

}

From source file:elaborate.tag_analysis.oosm.impl.gson.BaseInterfaceDeserializer.java

protected Object processArrayElement(String name, JsonArray element, Field field,
        JsonDeserializationContext jdc) throws JsonParseException {
    List list = new ArrayList();
    Class arrayElementType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
    for (int i = 0; i < element.size(); i++) {
        JsonObject jsonObject = element.get(i).getAsJsonObject();
        list.add(this.processNormalElement(null, jsonObject, arrayElementType, jdc));
    }/*from   w ww .jav  a  2  s  .co m*/
    return list;
}

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

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

    Mock mock = fieldDescriptor.getMock().get();
    Type fieldType = field.getGenericType();
    String fieldName = field.getName();
    DescriptorKey descriptorKey = new DescriptorKey(fieldType, fieldName);

    //if there is a parameter descriptor that matches the field then lets use that
    if (parameterDescriptors.containsKey(descriptorKey)) {
        ParameterDescriptor descriptor = parameterDescriptors.get(descriptorKey);
        Parameter parameter = descriptor.getParameter();
        Integer index = descriptor.getIndex();
        ResolvableType resolver = ResolvableType.forType(fieldType);

        Class rawType;//from  ww w . jav a2s .c o m

        if (resolver.hasGenerics()) {
            if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                rawType = resolver.getRawClass();
            } else {
                rawType = resolver.resolve();
            }
        } else {
            rawType = (Class) fieldType;
        }
        Object instance = testReifier.reifyField(fieldDescriptor, descriptor);
        arguments[index] = instance;
    } else {
        //otherwise find the right parameter based on the type of the field
        Collection<ParameterDescriptor> descriptors = parameterDescriptors.values();
        for (ParameterDescriptor descriptor : descriptors) {
            Parameter parameter = descriptor.getParameter();
            Type parameterType = parameter.getParameterizedType();
            Integer index = descriptor.getIndex();

            ResolvableType resolver = ResolvableType.forType(parameterType);

            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();
            }

            if (arguments[index] != null) {
                continue;
            }

            if (parameterType.equals(fieldType)) {
                Object instance = testReifier.reifyField(fieldDescriptor, descriptor);
                arguments[index] = instance;
                break;
            }

        }
    }

}

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

/**
 * Generates a {@link JavaType} that matches the target Thrift field represented by the provided
 * {@code <E>} enumerated value.  If the field's type includes generics, the generics will
 * be added to the generated {@link JavaType} to support proper conversion.
 * @param thriftInstance The Thrift-generated class instance that will be converted to/from JSON.
 * @param field A {@code <E>} enumerated value that represents a field in a Thrift-based entity.
 * @return The {@link JavaType} representation of the type associated with the field.
 * @throws NoSuchFieldException if unable to determine the field's type.
 * @throws SecurityException if unable to determine the field's type.
 *//*from ww  w . j av a2 s .  co m*/
protected JavaType generateValueType(final T thriftInstance, final E field)
        throws NoSuchFieldException, SecurityException {
    final TypeFactory typeFactory = TypeFactory.defaultInstance();

    final Field declaredField = thriftInstance.getClass().getDeclaredField(field.getFieldName());
    if (declaredField.getType().equals(declaredField.getGenericType())) {
        log.debug("Generating JavaType for type '{}'.", declaredField.getType());
        return typeFactory.constructType(declaredField.getType());
    } else {
        final ParameterizedType type = (ParameterizedType) declaredField.getGenericType();
        final Class<?>[] parameterizedTypes = new Class<?>[type.getActualTypeArguments().length];
        for (int i = 0; i < type.getActualTypeArguments().length; i++) {
            parameterizedTypes[i] = (Class<?>) type.getActualTypeArguments()[i];
        }
        log.debug("Generating JavaType for type '{}' with generics '{}'", declaredField.getType(),
                parameterizedTypes);
        return typeFactory.constructParametricType(declaredField.getType(), parameterizedTypes);
    }
}

From source file:org.jnosql.artemis.reflection.Reflections.java

/**
 * returns the generic type of field.// w w  w .ja va 2s. c o  m
 *
 * @param field the field
 * @return a generic type
 */
public Class<?> getGenericType(Field field) {
    ParameterizedType genericType = (ParameterizedType) field.getGenericType();
    return (Class<?>) genericType.getActualTypeArguments()[0];

}

From source file:com.adobe.acs.commons.util.impl.ReflectionUtilTest.java

@Test
public void test_isAssignableFrom() {

    Field numberField = FieldUtils.getDeclaredField(ReflectionUtilTest.class, "numberField");
    boolean isAssignableFrom = isAssignableFrom(numberField.getGenericType(), Integer.class);
    assertTrue(isAssignableFrom);/*w w w . ja  v  a 2s.c o m*/
}

From source file:org.jnosql.artemis.reflection.Reflections.java

/**
 * return the key and value of field./*from  ww w .jav  a2  s . c om*/
 *
 * @param field the field
 * @return the types of the type
 */
public KeyValueClass getGenericKeyValue(Field field) {
    ParameterizedType genericType = (ParameterizedType) field.getGenericType();
    KeyValueClass keyValueClass = new KeyValueClass();
    keyValueClass.keyClass = (Class<?>) genericType.getActualTypeArguments()[0];
    keyValueClass.valueClass = (Class<?>) genericType.getActualTypeArguments()[1];
    return keyValueClass;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.AbstractFieldPersistenceProvider.java

protected Class<?> getMapFieldType(Serializable instance, FieldManager fieldManager, Property property,
        PersistenceManager persistenceManager) {
    Class<?> returnType = null;
    Field field = fieldManager.getField(instance.getClass(),
            property.getName().substring(0, property.getName().indexOf(FieldManager.MAPFIELDSEPARATOR)));
    java.lang.reflect.Type type = field.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[1];
        Class<?>[] entities = persistenceManager.getDynamicEntityDao()
                .getAllPolymorphicEntitiesFromCeiling(clazz);
        if (!ArrayUtils.isEmpty(entities)) {
            returnType = entities[entities.length - 1];
        }/*  w w w .  j  a  v  a2s  .  c  om*/
    }
    return returnType;
}

From source file:com.heisenberg.impl.plugin.Descriptors.java

public Descriptor getDataTypeDescriptor(Field field) {
    return getDataTypeDescriptor(field.getGenericType(), field);
}

From source file:richtercloud.reflection.form.builder.fieldhandler.AbstractListFieldHandler.java

@Override
public JComponent handle(Field field, Object instance, FieldUpdateListener<E> updateListener,
        R reflectionFormBuilder) throws IllegalArgumentException, IllegalAccessException,
        FieldHandlingException, InstantiationException, InvocationTargetException {
    Type fieldGenericType = field.getGenericType();
    Pair<JComponent, ComponentHandler<?>> retValue = this.typeHandler.handle(fieldGenericType,
            (T) field.get(instance), //fieldValue
            field.getName(), field.getDeclaringClass(), //declaringClass
            updateListener, reflectionFormBuilder);
    return retValue.getKey();
}