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.fusesource.ide.generator.Generator.java

private Class<?> elementTypeClass(Property<?> prop) {
    if (isJavaCollection(prop)) {
        if (prop instanceof FieldProperty) {
            FieldProperty fieldProp = (FieldProperty) prop;
            Field fld = fieldProp.getField();
            return elementTypeClass(fld.getGenericType());
        }/* w  w  w .j  a  v a  2s.c  om*/
        if (prop instanceof BeanProperty) {
            BeanProperty beanProp = (BeanProperty) prop;
            Method readMethod = beanProp.descriptor().getReadMethod();
            if (readMethod != null) {
                return elementTypeClass(readMethod.getGenericReturnType());
            }
        }
    }
    return null;
}

From source file:wwutil.jsoda.DynamoDBService.java

private Object attrToValue(Field field, AttributeValue attr) throws Exception {
    // Handle Set<String>, Set<Long>, or Set<Integer> field.
    if (Set.class.isAssignableFrom(field.getType())) {
        Class paramType = ReflectUtil.getGenericParamType1(field.getGenericType());
        if (isMultiValuetype(paramType)) {
            if (isN(paramType))
                return DataUtil.toObjectSet(attr.getNS(), paramType);
            else//w  w w  . ja va 2  s .  com
                return DataUtil.toObjectSet(attr.getSS(), paramType);
        }
    }

    // Handle number types
    if (isN(field.getType())) {
        return ConvertUtils.convert(attr.getN(), field.getType());
    }

    // Delegate to DataUtil to decode the rest.
    return DataUtil.decodeAttrStrToValue(attr.getS(), field.getType());
}

From source file:org.raml.emitter.RamlEmitter.java

private void dumpMappingField(StringBuilder dump, int depth, Field field, boolean implicit, Object pojo) {
    if (!Map.class.isAssignableFrom(field.getType())) {
        throw new RuntimeException("invalid type");
    }/*w  ww .  j  a  va 2  s .  com*/

    Map value = (Map) getFieldValue(field, pojo);

    if (value == null || value.isEmpty()) {
        return;
    }

    if (!implicit) {
        dump.append(indent(depth)).append(alias(field)).append(YAML_MAP_SEP).append("\n");
        depth++;
    }

    ParameterizedType pType = (ParameterizedType) field.getGenericType();
    Type valueType = pType.getActualTypeArguments()[1];
    dumpMap(dump, depth, valueType, value);
}

From source file:org.romaframework.core.schema.reflection.SchemaClassReflection.java

private void readClass() {
    Class<?> iClass = (Class<?>) (javaClass != null ? javaClass : superClass.getLanguageType());

    ParameterizedType type = SchemaHelper.resolveParameterizedType(iClass);

    List<Method> methods = SchemaHelper.getMethods(iClass);
    List<Method> eventsToAdd = new ArrayList<Method>();
    for (Method method : methods) {
        // JUMP STATIC FIELDS OR NOT PUBLIC FIELDS
        if (isToIgnoreMethod(method))
            continue;
        if (initGetterForField(method, type) || initSetterForField(method, type))
            continue;
        else if (isEvent(method)) {
            eventsToAdd.add(method);//from  w ww. j  av  a2 s . c  o m
            continue;
        } else
            createAction(method, type);

    }

    Field[] javaFields = iClass.getDeclaredFields();
    for (Field curField : javaFields) {
        SchemaField sf = getField(curField.getName());
        if (sf instanceof SchemaFieldReflection) {
            Class<?> genericFieldClass = SchemaHelper.resolveClassFromType(curField.getGenericType(), type);
            SchemaClass fieldSchemaClass = Roma.schema().getSchemaClassIfExist(genericFieldClass);
            if (sf.getType() == null || fieldSchemaClass.isAssignableAs(sf.getType().getSchemaClass())) {
                sf.setType(fieldSchemaClass);
                ((SchemaFieldReflection) sf).field = curField;
                ((SchemaFieldReflection) sf).languageType = genericFieldClass;
            }
        }
    }

    List<SchemaField> curFields = new ArrayList<SchemaField>(fields.values());
    for (SchemaField field : curFields) {
        if ((field instanceof SchemaFieldReflection && !(field instanceof SchemaFieldDelegate))
                && ((SchemaFieldReflection) field).getGetterMethod() == null) {
            fields.remove(field.getName());
            orderedFields.remove(field);
        } else {
            if (field instanceof SchemaFieldReflection)
                ((SchemaFieldReflection) field).configure();
            field.setOrder(getFieldOrder(field));
        }
    }
    Collections.sort(orderedFields);

    List<SchemaAction> curActions = new ArrayList<SchemaAction>(actions.values());

    for (SchemaAction action : curActions) {
        if (action instanceof SchemaActionReflection)
            ((SchemaActionReflection) action).configure();
        action.setOrder(getActionOrder(action));
    }
    Collections.sort(orderedActions);

    addEvents(eventsToAdd);

    List<SchemaEvent> curEvents = new ArrayList<SchemaEvent>(events.values());
    for (SchemaEvent event : curEvents) {
        if (event instanceof SchemaEventReflection)
            ((SchemaEventReflection) event).configure();
        event.setOrder(getActionOrder(event));
    }
    Collections.sort(orderedActions);
}

From source file:org.dd4t.databind.builder.json.JsonModelConverter.java

private <T extends BaseViewModel> void deserializeAndBuildModels(final T model, final String fieldName,
        final Field modelField, final FieldType tridionDataFieldType, final List<JsonNode> nodeList)
        throws SerializationException, IllegalAccessException, IOException {
    if (modelField.getType().equals(List.class)) {
        final Type parametrizedType = TypeUtils.getRuntimeTypeOfTypeParameter(modelField.getGenericType());
        LOG.debug("Interface check: " + TypeUtils.classIsViewModel((Class<?>) parametrizedType));

        if (TypeUtils.classIsViewModel((Class<?>) parametrizedType)
                || databinder.classHasViewModelDerivatives(((Class<?>) parametrizedType).getCanonicalName())) {
            for (JsonNode node : nodeList) {

                if (!node.has(DataBindConstants.ROOT_ELEMENT_NAME)) {
                    checkTypeAndBuildModel(model, fieldName, node, modelField, (Class<T>) parametrizedType);
                } else {
                    LOG.debug("not handling a schemaNode.");
                }/*w w w  . j av a  2s  .c  o m*/
            }

        } else {
            for (JsonNode node : nodeList) {
                if (!node.has(DataBindConstants.ROOT_ELEMENT_NAME)) {
                    deserializeGeneric(model, node, modelField, tridionDataFieldType);
                } else {
                    LOG.debug("not handling a schemaNode.");
                }
            }
        }

    } else if (TypeUtils.classIsViewModel(modelField.getType())
            || databinder.classHasViewModelDerivatives(modelField.getType().getCanonicalName())) {
        final Class<T> modelClassToUse = (Class<T>) modelField.getType();
        checkTypeAndBuildModel(model, fieldName, nodeList.get(0), modelField, modelClassToUse);
    } else {
        deserializeGeneric(model, nodeList.get(0), modelField, tridionDataFieldType);
    }
}

From source file:fr.mby.utils.spring.beans.factory.BasicProxywiredManager.java

/**
 * Find Bean Type to inject (not the generic type like Collection or Set).
 * // w w  w  .j a  v  a  2s. c  o m
 * @param descriptor
 * @param autowiredBeanNames
 * @return
 */
protected Class<?> getBeanType(final DependencyDescriptor descriptor, final Set<String> autowiredBeanNames) {
    final Class<?> result;

    Type fieldType = null;

    final Field field = descriptor.getField();
    if (field == null) {
        // Annotation on the method
        final MethodParameter methodParameter = descriptor.getMethodParameter();
        if (methodParameter != null) {
            fieldType = methodParameter.getGenericParameterType();
        }
    } else {
        fieldType = field.getGenericType();
    }

    if (fieldType != null) {
        final Class<?> type = descriptor.getDependencyType();
        if (Collection.class.isAssignableFrom(type)) {
            final ParameterizedType parameterizedType = (ParameterizedType) fieldType;
            result = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        } else if (Map.class.isAssignableFrom(type)) {
            final ParameterizedType parameterizedType = (ParameterizedType) fieldType;
            result = (Class<?>) parameterizedType.getActualTypeArguments()[1];
        } else if (type.isArray()) {
            // We can't do anything
            throw new IllegalStateException("You cannot use Proxywired annotation on an Array !");
        } else {
            result = type;
        }
    } else {
        throw new IllegalStateException("Unable to find the Bean type !");
    }

    return result;
}

From source file:cn.bzvs.excel.imports.base.ImportBaseService.java

/**
 * ??//from  ww w.jav a2 s  . c o m
 * @param targetId
 * @param fields
 * @param excelParams
 * @param excelCollection
 * @param pojoClass
 * @param getMethods
 * @throws Exception
 */
public void getAllExcelField(String targetId, Field[] fields, Map<String, ExcelImportEntity> excelParams,
        List<ExcelCollectionParams> excelCollection, Class<?> pojoClass, List<Method> getMethods)
        throws Exception {
    ExcelImportEntity excelEntity = null;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (PoiPublicUtil.isNotUserExcelUserThis(null, field, targetId)) {
            continue;
        }
        if (PoiPublicUtil.isCollection(field.getType())) {
            // ?
            ExcelCollection excel = field.getAnnotation(ExcelCollection.class);
            ExcelCollectionParams collection = new ExcelCollectionParams();
            collection.setName(field.getName());
            Map<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>();
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            collection.setType(clz);
            getExcelFieldList(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(clz), clz, temp, null);
            collection.setExcelParams(temp);
            collection.setExcelName(PoiPublicUtil
                    .getValueByTargetId(field.getAnnotation(ExcelCollection.class).name(), targetId, null));
            additionalCollectionName(collection);
            excelCollection.add(collection);
        } else if (PoiPublicUtil.isJavaClass(field)) {
            addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, excelParams);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            //
            newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            ExcelEntity excel = field.getAnnotation(ExcelEntity.class);
            getAllExcelField(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(field.getType()), excelParams, excelCollection,
                    field.getType(), newMethods);
        }
    }
}

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java

/**
 * Encapsulates a field in a {@link ValueDefinition} so that it can be registered for updates.
 * /*from w  ww.  ja  v  a  2s. c o m*/
 * @param field
 *            the field being processed
 * @param valueList
 *            the list of value definitions that the new {@link ValueDefinition} for this field will be added to.
 * @param bean
 *            the bean being configured.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void processField(Field field, List<ValueDefinition<?, ?>> valueList, Object bean) {
    Configured annotation = field.getAnnotation(Configured.class);
    if (annotation != null) {
        Class type = field.getType();
        boolean list = false;
        ValueDefinition<Object, ?> value;
        if (type == List.class) {
            type = listType(field.getGenericType());
            FieldValueChangeListener<List<Object>> listener = new FieldValueChangeListener<List<Object>>(field,
                    bean, type, list);
            value = new ValueListDefinition<Object>(type, annotation.value(), listener);
        } else {
            FieldValueChangeListener<Object> listener = new FieldValueChangeListener<Object>(field, bean, type,
                    list);
            value = new SingleValueDefinition<Object>(type, annotation.value(), listener);
        }
        valueList.add(value);
    }
}

From source file:wwutil.jsoda.DynamoDBService.java

private AttributeValue valueToAttr(Field field, Object value) {
    // Don't set the AttributeValue for null value
    if (value == null)
        return null;

    // Handle Set<String>, Set<Long>, or Set<Integer> field.
    if (Set.class.isAssignableFrom(field.getType())) {
        Class paramType = ReflectUtil.getGenericParamType1(field.getGenericType());
        if (isMultiValuetype(paramType)) {
            if (isN(paramType)) {
                return new AttributeValue().withNS(DataUtil.toStringSet((Set) value, paramType));
            } else {
                return new AttributeValue().withSS(DataUtil.toStringSet((Set) value, paramType));
            }//from   w ww. j ava2s  .c  o m
        }
    }

    // Handle number types
    if (isN(field.getType())) {
        return new AttributeValue().withN(value.toString());
    }

    // Delegate to DataUtil to encode the rest.
    return new AttributeValue().withS(DataUtil.encodeValueToAttrStr(value, field.getType()));
}

From source file:cn.afterturn.easypoi.excel.imports.base.ImportBaseService.java

/**
 * ??//from  w  w  w  .  j a v a 2s. c  om
 * @param targetId
 * @param fields
 * @param excelParams
 * @param excelCollection
 * @param pojoClass
 * @param getMethods
 * @throws Exception
 */
public void getAllExcelField(String targetId, Field[] fields, Map<String, ExcelImportEntity> excelParams,
        List<ExcelCollectionParams> excelCollection, Class<?> pojoClass, List<Method> getMethods,
        ExcelEntity excelEntityAnn) throws Exception {
    ExcelImportEntity excelEntity = null;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (PoiPublicUtil.isNotUserExcelUserThis(null, field, targetId)) {
            continue;
        }
        if (PoiPublicUtil.isCollection(field.getType())) {
            // ?
            ExcelCollection excel = field.getAnnotation(ExcelCollection.class);
            ExcelCollectionParams collection = new ExcelCollectionParams();
            collection.setName(field.getName());
            Map<String, ExcelImportEntity> temp = new HashMap<String, ExcelImportEntity>();
            ParameterizedType pt = (ParameterizedType) field.getGenericType();
            Class<?> clz = (Class<?>) pt.getActualTypeArguments()[0];
            collection.setType(clz);
            getExcelFieldList(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(clz), clz, temp, null);
            collection.setExcelParams(temp);
            collection.setExcelName(PoiPublicUtil
                    .getValueByTargetId(field.getAnnotation(ExcelCollection.class).name(), targetId, null));
            additionalCollectionName(collection);
            excelCollection.add(collection);
        } else if (PoiPublicUtil.isJavaClass(field) || field.getType().isEnum()) {
            addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, excelParams, excelEntityAnn);
        } else {
            List<Method> newMethods = new ArrayList<Method>();
            if (getMethods != null) {
                newMethods.addAll(getMethods);
            }
            //
            newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
            ExcelEntity excel = field.getAnnotation(ExcelEntity.class);
            if (excel.show() && StringUtils.isEmpty(excel.name())) {
                throw new ExcelImportException("if use ExcelEntity ,name mus has value ,data: "
                        + ReflectionToStringBuilder.toString(excel), ExcelImportEnum.PARAMETER_ERROR);
            }
            getAllExcelField(StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId,
                    PoiPublicUtil.getClassFields(field.getType()), excelParams, excelCollection,
                    field.getType(), newMethods, excel);
        }
    }
}