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:org.eclipse.smarthome.config.core.internal.ConfigMapper.java

/**
 * Use this method to automatically map a configuration collection to a Configuration holder object. A common
 * use-case would be within a service. Usage example:
 *
 * <pre>/* ww w  . ja v  a2  s . c om*/
 * {@code
 *   public void modified(Map<String, Object> properties) {
 *     YourConfig config = ConfigMapper.as(properties, YourConfig.class);
 *   }
 * }
 * </pre>
 *
 *
 * @param properties The configuration map.
 * @param configurationClass The configuration holder class. An instance of this will be created so make sure that
 *            a default constructor is available.
 * @return The configuration holder object. All fields that matched a configuration option are set. If a required
 *         field is not set, null is returned.
 */
public static <T> @Nullable T as(Map<String, Object> properties, Class<T> configurationClass) {
    T configuration = null;
    try {
        configuration = configurationClass.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        return null;
    }

    List<Field> fields = getAllFields(configurationClass);
    for (Field field : fields) {
        // Don't try to write to final fields and ignore transient fields
        if (Modifier.isFinal(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        String fieldName = field.getName();
        String configKey = fieldName;
        Class<?> type = field.getType();

        Object value = properties.get(configKey);

        // Consider RequiredField annotations
        if (value == null) {
            logger.trace("Skipping field '{}', because config has no entry for {}", fieldName, configKey);
            continue;
        }

        // Allows to have List<int>, List<Double>, List<String> etc
        if (value instanceof Collection) {
            Collection<?> c = (Collection<?>) value;
            Class<?> innerClass = (Class<?>) ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments()[0];
            final List<Object> lst = new ArrayList<>(c.size());
            for (final Object it : c) {
                final Object normalized = objectConvert(it, innerClass);
                lst.add(normalized);
            }
            value = lst;
        }

        try {
            value = objectConvert(value, type);
            logger.trace("Setting value ({}) {} to field '{}' in configuration class {}", type.getSimpleName(),
                    value, fieldName, configurationClass.getName());
            FieldUtils.writeField(configuration, fieldName, value, true);

        } catch (Exception ex) {
            logger.warn("Could not set field value for field '{}': {}", fieldName, ex.getMessage(), ex);
        }
    }

    return configuration;
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.matchers.FieldMatcher.java

/** {@inheritDoc} */
@Override/*from  w  w  w. ja v a 2 s .c  om*/
public Type extractGenericType(final Field type) {
    Validate.notNull(type, FieldMatcher.FIELD_NULL);
    return type.getGenericType();
}

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

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

    Mock mock = fieldDescriptor.getMock().get();
    String mockName = mock.name();
    DescriptorKey descriptorKey = new DescriptorKey(fieldType, mockName);

    ParameterDescriptor parameterDescriptor = parameterDescriptors.get(descriptorKey);

    checkArgument(parameterDescriptor != null,
            "Can not mock field '%s'. Could not find class under test constructor "
                    + "argument with the name '%s'.",
            field.getName(), mockName);/*from   ww  w .j a v a  2  s  .c  o  m*/

    Parameter parameter = parameterDescriptor.getParameter();
    Integer index = parameterDescriptor.getIndex();
    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' with name '%s' do not match.",
            field.getName(), field.getGenericType(), parameterType, mockName);

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

From source file:net.larry1123.elec.util.config.ConfigFile.java

/**
 * Load data from disk and if a key is miss it will create it.
 *//*from w  w w .  j  a  v  a2  s  .c  o  m*/
public void load() {
    for (Field field : configFields) {
        FieldHandler<?> fieldHandler = factory.createFieldHandler(field.getGenericType(), field, config);
        fieldHandler.load();
        fieldHandler.setComments();
    }
    // Well lets SAVE!!!
    config.getPropertiesFile().save();
}

From source file:net.larry1123.elec.util.config.ConfigFile.java

/**
 * Saves data to disk if any change has been made
 *//* w  w w.  j  ava 2s .  c  om*/
public void save() {
    for (Field field : configFields) {
        FieldHandler<?> fieldHandler = factory.createFieldHandler(field.getGenericType(), field, config);
        fieldHandler.save();
        fieldHandler.setComments();
    }
    // Well lets SAVE!!!
    config.getPropertiesFile().save();
}

From source file:nl.knaw.huygens.timbuctoo.storage.graph.tinkerpop.conversion.property.PropertyConverterFactory.java

private Class<?> getComponentType(Field field) {
    Type[] actualTypeArguments = ((ParameterizedType) field.getGenericType()).getActualTypeArguments();

    if (actualTypeArguments.length <= 0) {
        return null;
    }//from  w  w w.  ja  v a2  s .  c om

    Type firstTypeArgument = actualTypeArguments[0];
    return firstTypeArgument instanceof Class<?> ? (Class<?>) firstTypeArgument : null;

}

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

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

From source file:com.qmetry.qaf.automation.ui.webdriver.ElementFactory.java

private Class<?> getListType(Field field) {
    Type genericType = field.getGenericType();
    Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
    return (Class<?>) listType;

}

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

protected FieldInfo buildFieldInfo(Field field) {
    FieldInfo info = new FieldInfo();
    info.setName(field.getName());//from w ww  . j a va 2s.  co m
    info.setGenericType(field.getGenericType());
    ManyToMany manyToMany = field.getAnnotation(ManyToMany.class);
    if (manyToMany != null) {
        info.setManyToManyMappedBy(manyToMany.mappedBy());
        info.setManyToManyTargetEntity(manyToMany.targetEntity().getName());
    }
    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
    if (oneToMany != null) {
        info.setOneToManyMappedBy(oneToMany.mappedBy());
        info.setOneToManyTargetEntity(oneToMany.targetEntity().getName());
    }
    return info;
}

From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java

/**
 * Infers the data type for the specified field.
 *
 * @author paouelle// ww w.j  a v a 2 s.  c om
 *
 * @param  field the non-<code>null</code> field to infer the CQL data type for
 * @param  clazz the non-<code>null</code> class for which to infer the CQL
 *         data type for the field
 * @param  types the non-<code>null</code> list where to add the inferred type and
 *         its arguments
 * @param  persisted the persisted annotation to consider for the field
 * @throws IllegalArgumentException if the data type cannot be inferred from
 *         the field
 */
private static void inferDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types,
        Persisted persisted) {
    if (Optional.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of optionals is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // optional will always have 1 argument

            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferBasicDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types,
                        persisted);
            }
            return;
        }
    } else if (List.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // lists will always have 1 argument

            types.add(DataType.LIST);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types);
            }
            return;
        }
    } else if (Set.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // sets will always have 1 argument

            types.add(DataType.SET);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types);
            }
            return;
        }
    } else if (Map.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type ktype = ptype.getActualTypeArguments()[0]; // maps will always have 2 arguments
            final Type vtype = ptype.getActualTypeArguments()[1]; // maps will always have 2 arguments

            types.add(DataType.MAP);
            // don't consider the @Persister annotation for the key
            DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(ktype), types, null);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(vtype), types);
            }
            return;
        }
    }
    DataTypeImpl.inferBasicDataTypeFrom(field, clazz, types, persisted);
}