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.raml.emitter.RamlEmitterV2.java

/**
 * <p>dumpSequenceField.</p>
 *
 * @param dump a {@link java.lang.StringBuilder} object.
 * @param depth a int./*from   w  ww.  java 2  s .  co  m*/
 * @param field a {@link java.lang.reflect.Field} object.
 * @param pojo a {@link java.lang.Object} object.
 */
@SuppressWarnings("rawtypes")
public void dumpSequenceField(StringBuilder dump, int depth, Field field, Object pojo) {
    if (!List.class.isAssignableFrom(field.getType())) {
        throw new RuntimeException("Only List can be sequence.");
    }
    currentField = field;

    List seq = (List) getFieldValue(field, pojo);
    if (seq == null || seq.size() == 0) {
        return;
    }

    Type type = field.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        Type itemType = pType.getActualTypeArguments()[0];
        dump.append(indent(depth)).append(alias(field)).append(YAML_MAP_SEP);
        dumpSequenceItems(dump, depth, seq, itemType, false);
    }
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ??/*ww w .ja v a 2 s. co m*/
 * 
 * @param name
 * @return
 */
public Type getFieldGenericType(Field field) {
    Assert.notNull(field);
    ClassEx cw = this;
    if (field.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, field.getDeclaringClass());
        cw = new ClassEx(type);
    }
    return BeanUtils.getBoundType(field.getGenericType(), cw);
}

From source file:com.datatorrent.stram.plan.logical.LogicalPlan.java

public static Type getPortType(Field f) {
    if (f.getGenericType() instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) f.getGenericType();
        //LOG.debug("Field type is parameterized: " + Arrays.asList(t.getActualTypeArguments()));
        //LOG.debug("rawType: " + t.getRawType()); // the port class
        Type typeArgument = t.getActualTypeArguments()[0];
        if (typeArgument instanceof Class) {
            return typeArgument;
        } else if (typeArgument instanceof TypeVariable) {
            TypeVariable<?> tv = (TypeVariable<?>) typeArgument;
            LOG.debug("bounds: " + Arrays.asList(tv.getBounds()));
            // variable may contain other variables, java.util.Map<java.lang.String, ? extends T2>
            return tv.getBounds()[0];
        } else if (typeArgument instanceof GenericArrayType) {
            LOG.debug("type {} is of GenericArrayType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof WildcardType) {
            LOG.debug("type {} is of WildcardType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof ParameterizedType) {
            return typeArgument;
        } else {/*from w ww. j a  v a2 s .com*/
            LOG.error("Type argument is of expected type {}", typeArgument);
            return null;
        }
    } else {
        // ports are always parameterized
        LOG.error("No type variable: {}, typeParameters: {}", f.getType(),
                Arrays.asList(f.getClass().getTypeParameters()));
        return null;
    }
}

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private EntityModel createBeanEntity(Class clazz, RegistryNodeModel registryNodeModel,
        List<RelationshipModel> relationships, Map<String, EntityModel> models) {
    if (clazz == Object.class)
        return null;

    EntityModel model = models.get(clazz.getName());
    if (model != null)
        return model;

    String name = clazz.getSimpleName().replaceAll("\\B([A-Z]+)\\B", " $1");

    EntityModel entityModel;/* w w w .j  a  va  2  s  . c  o m*/
    if (clazz.isMemberClass()) {
        entityModel = new SubEntityModel();
        name = "Nested " + name;
        registryNodeModel = models.get(clazz.getEnclosingClass().getName());
    } else {
        entityModel = new EntityModel();
    }

    models.put(clazz.getName(), entityModel);

    entityModel.setName(name);
    entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), name));
    entityModel.setPath(registryNodeModel.getLookup());
    entityModel.setAbstractEntity(Modifier.isAbstract(clazz.getModifiers()));
    entityModel.setTypeEntity(true);
    entityModel.setReverseEngineer(true);
    entityModel.setExtendedEntity(
            createBeanEntity(clazz.getSuperclass(), registryNodeModel, relationships, models));
    entityModel.setProtocol(EntityProtocol.HTTP);
    entityModel.setParent(registryNodeModel);

    Field[] declaredFields = clazz.getDeclaredFields();
    List<FieldModel> fields = new ArrayList<FieldModel>(declaredFields.length);

    for (Field field : declaredFields) {
        analyzeField(field.getName(), field.getGenericType(), TYPE, entityModel,
                field.getAnnotation(XmlElement.class), models, relationships, fields);

        XmlElements xmlElements = field.getAnnotation(XmlElements.class);
        if (xmlElements != null) {
            XmlElement[] elements = xmlElements.value();
            List<EntityModel> options = new ArrayList<EntityModel>(elements.length);
            RegistryNodeModel parent = clazz.isMemberClass() ? registryNodeModel.getParent()
                    : registryNodeModel;
            for (XmlElement element : elements) {
                if (element.type().isAnnotationPresent(XmlAccessorType.class)) {
                    EntityModel entity = createBeanEntity(element.type(), parent, relationships, models);
                    options.add(entity);
                }
            }
            FieldModel fieldModel = fields.get(fields.size() - 1);
            fieldModel.setOptions(options);
        }
    }

    entityModel.setFields(fields);

    return entityModel;
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

/**
 * Return the component type of a field, or String.class if the type cannot be found.
 * @param field The reflected field to inspect.
 * @return The parameterized component type, or String.class if the parameterized type could not be found.
 * @throws IllegalArgumentException If more than one parameterized type is found on the field.
 *//*from   w  w w.  ja  v  a  2s  .c  om*/
@Override
protected Type getCollectionComponentType(Field field) {
    // Multiplex arguments must resolve to maps from which the clp should extract the second type.
    if (field.getGenericType() instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        if (parameterizedType.getActualTypeArguments().length != 2)
            throw new IllegalArgumentException(
                    "Unable to determine collection type of field: " + field.toString());
        return (Class) parameterizedType.getActualTypeArguments()[1];
    } else
        return String.class;
}

From source file:org.jiemamy.entity.io.meta.impl.PropertyMetaFactoryImpl.java

private void doOneToMany(PropertyMeta propertyMeta, Field field, EntityMeta entityMeta, OneToMany oneToMany)
        throws OneToManyNotListException, OneToManyNotGenericsException, RelationshipNotEntityException,
        BothMappedByAndJoinColumnException, MappedByMandatoryException {
    Validate.notNull(propertyMeta);//from   w  w w .j ava  2 s .co m
    Validate.notNull(field);
    Validate.notNull(entityMeta);
    Validate.notNull(oneToMany);
    propertyMeta.setRelationshipType(RelationshipType.ONE_TO_MANY);
    if (List.class.isAssignableFrom(field.getType()) == false) {
        throw new OneToManyNotListException(entityMeta.getName(), propertyMeta.getName());
    }
    Class<?> relationshipClass = ReflectionUtil.getElementTypeOfList(field.getGenericType());
    if (relationshipClass == null) {
        throw new OneToManyNotGenericsException(entityMeta.getName(), propertyMeta.getName());
    }
    if (relationshipClass.getAnnotation(Entity.class) == null) {
        throw new RelationshipNotEntityException(entityMeta.getName(), propertyMeta.getName(),
                relationshipClass);
    }
    propertyMeta.setRelationshipClass(relationshipClass);
    String mappedBy = oneToMany.mappedBy();
    if (!StringUtils.isEmpty(mappedBy)) {
        if (propertyMeta.getJoinColumnMetaList().size() > 0) {
            throw new BothMappedByAndJoinColumnException(entityMeta.getName(), propertyMeta.getName());
        }
        propertyMeta.setMappedBy(mappedBy);
    } else {
        throw new MappedByMandatoryException(entityMeta.getName(), propertyMeta.getName());
    }
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

/**
 * Return the component type of a field, or String.class if the type cannot be found.
 * @param field The reflected field to inspect.
 * @return The parameterized component type, or String.class if the parameterized type could not be found.
 * @throws IllegalArgumentException If more than one parameterized type is found on the field.
 */// w ww . jav a 2  s .co m
@Override
protected Type getCollectionComponentType(Field field) {
    // If this is a parameterized collection, find the contained type.  If blow up if more than one type exists.
    if (field.getGenericType() instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        if (parameterizedType.getActualTypeArguments().length > 1)
            throw new IllegalArgumentException(
                    "Unable to determine collection type of field: " + field.toString());
        return parameterizedType.getActualTypeArguments()[0];
    } else
        return String.class;
}

From source file:org.synku4j.wbxml.marshal.impl.MarshalDelegate.java

/**
 *//*from   w ww  .jav a 2 s  . com*/
private void processField(final WbxmlContext cntx, OutputStream os, Field field, Object target,
        WbxmlPage currentPage, String[] filters) throws IOException, WbxmlMarshallerException {
    if (log.isDebugEnabled()) {
        log.debug("processField field = " + field);
    }

    // TODO: Check to see if the filters match.

    field.setAccessible(true);

    final WbxmlField wbxmlField = field.getAnnotation(WbxmlField.class);

    //
    // A Ghost element is a container for elements which will be parsed.
    // Do not generate a start or end element for this field.
    //
    final boolean ghostElement = wbxmlField.index() == WbxmlField.NO_INDEX;
    if (ghostElement) {
        if (log.isDebugEnabled()) {
            log.debug("ghost element :" + wbxmlField);
        }
    }

    final Type fieldType = field.getGenericType();

    Object value = null;
    try {
        value = field.get(target);
    } catch (Exception e) {
        // This will terminate the marshaling. Is this always right ?
        if (log.isWarnEnabled()) {
            log.warn("Exception thrown getting value via field (" + field + ")", e);
        }
        throw new WbxmlMarshallerException(e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Value of field (" + field + ") = " + value);
    }

    if (value == null) {
        if (wbxmlField != null && wbxmlField.required()) {
            throw new WbxmlMarshallerException("Field (" + wbxmlField.name()
                    + "), is marked required but is null. Processing cannot continue.");
        }

        if (log.isDebugEnabled()) {
            log.debug("Field (" + wbxmlField.name() + ") is null, it will not be written to the stream.");
        }

        return;
    } else if (Collection.class.isAssignableFrom(value.getClass())) {
        if (log.isDebugEnabled()) {
            log.debug("Field (" + wbxmlField.name() + ") is a collection");
        }

        // TODO :
        //
        // in the case of a collection of strings we need to
        // wrap each entry in the defined wbxml field.
        // Objects need to be marshalled.
        //

        // We have a collection, marshal through the values;
        final Collection<?> values = (Collection<?>) value;
        if (wbxmlField.required() && values.isEmpty()) {
            throw new WbxmlMarshallerException("Field (" + wbxmlField.name()
                    + "), is marked required but is empty. Processing cannot continue.");
        }

        if (!ghostElement) {
            pushElement(cntx, os, wbxmlField.index(), true);
        }

        // Get field type for each item as it may not be declared on the 
        WbxmlField innerField;
        for (Object obj : values) {
            innerField = getWbxmlField(obj.getClass(), false);

            if (ghostElement && innerField != null) {
                pushElement(cntx, os, innerField.index(), true);
            }

            if (obj instanceof String) {
                if (cntx.isOpaqueStrings()) {
                    pushOpaque(cntx, os, innerField.index(), obj.toString().getBytes());
                } else {
                    inlineString(cntx, os, obj.toString());
                }
            } else {
                doMarshal(cntx, os, obj, currentPage, filters);
            }

            if (ghostElement && innerField != null) {
                popElement(cntx, os);
            }
        }

        if (!ghostElement) {
            popElement(cntx, os);
        }
    } else if (value instanceof byte[]) {
        pushOpaque(cntx, os, wbxmlField.index(), (byte[]) value);
    } else if (value instanceof Boolean) {
        pushElement(cntx, os, wbxmlField.index(), false);
    } else {
        final Class<?> valueClass = value.getClass();

        if (!ghostElement) {
            pushElement(cntx, os, wbxmlField.index(), true);
        }

        final WbxmlPage page = valueClass.getAnnotation(WbxmlPage.class);
        if (page != null) {
            doMarshal(cntx, os, value, page, filters);
        } else {
            if (cntx.isOpaqueStrings()) {
                opaque(cntx, os, value.toString().getBytes());
            } else {
                inlineString(cntx, os, value.toString());
            }
        }

        if (!ghostElement) {
            popElement(cntx, os);
        }
    }
}

From source file:org.tinygroup.context2object.impl.ClassNameObjectGenerator.java

private Object buildObject(String varName, Object object, Context context, String preName) {
    if (object == null) {
        return null;
    }//from   ww  w . j  ava  2 s  . co  m
    Class<?> clazz = object.getClass();

    String objName = varName;
    ObjectAssembly assembly = getObjectAssembly(object.getClass());
    if (assembly != null) {
        assembly.assemble(varName, object, context);
        return object;
    }
    // 20130424
    // ?
    boolean allPropertyNull = true;
    if (isNull(objName)) {
        objName = getObjName(object);
    }
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(object.getClass())) {
        if (descriptor.getPropertyType().equals(Class.class)) {
            continue;
        }

        // 201402025?propertyName?
        // String propertyName = getPropertyName(clazz,
        // descriptor.getName());
        String propertyName = descriptor.getName();
        Object propertyValue = getPerpertyValue(preName, objName, propertyName, context);// user.name,user_name,name
        if (propertyValue != null) { // ????
            try {
                if (descriptor.getPropertyType().equals( // ?()
                        propertyValue.getClass())
                        || implmentInterface(propertyValue.getClass(), descriptor.getPropertyType())) {
                    BeanUtils.setProperty(object, descriptor.getName(), propertyValue);
                    allPropertyNull = false;
                    continue;
                } else if (isSimpleType(descriptor.getPropertyType())) {// ?
                    if (String.class == propertyValue.getClass()) { // String
                        BeanUtils.setProperty(object, descriptor.getName(), BasicTypeConverter
                                .getValue(propertyValue.toString(), descriptor.getPropertyType().getName()));
                        allPropertyNull = false;
                    } else if (isSimpleType(propertyValue.getClass())) { // ?????
                        BeanUtils.setProperty(object, descriptor.getName(), propertyValue.toString());
                        allPropertyNull = false;
                    } else {
                        LOGGER.logMessage(LogLevel.WARN,
                                "?{0}.{1},{3},{4}", objName,
                                propertyName, descriptor.getPropertyType(), propertyValue.getClass());
                    }
                    continue;
                }
                // else {
                // }
                // ???
            } catch (Exception e) {
                LOGGER.errorMessage("{0}", e, descriptor.getName());
            }
        }

        // ????
        // ???
        TypeConverter typeConverter = getTypeConverter(descriptor.getPropertyType());
        if (typeConverter != null) {
            if (propertyValue != null) {
                try {
                    BeanUtils.setProperty(object, descriptor.getName(), typeConverter.getObject(propertyValue));
                    allPropertyNull = false;
                } catch (Exception e) {
                    LOGGER.errorMessage("{0}", e, descriptor.getName());
                }
            }
            continue;
        }
        // ??
        if (!isSimpleType(descriptor.getPropertyType())) {
            // 
            try {
                String newPreName = getReallyPropertyName(preName, objName, propertyName);
                // ===============begin======================
                // 20151208getDeclaredFieldWithParent?type???
                // Class<?> type = null;
                // try{
                Field field = getDeclaredFieldWithParent(clazz, propertyName);
                // type =
                // clazz.getDeclaredField(descriptor.getName()).getType();
                // type = descriptor.getPropertyType();
                // }catch (NoSuchFieldException e)

                if (field == null) {
                    LOGGER.logMessage(LogLevel.WARN, "{}?{}", clazz.getName(), propertyName);
                    continue;
                }
                Class<?> type = field.getType();
                // ===============end======================
                if (type.isArray()) {// 
                    Object value = getObject(newPreName, null, descriptor.getPropertyType(), context, null);
                    if (value != null) {
                        BeanUtils.setProperty(object, descriptor.getName(), value);
                        allPropertyNull = false;
                    }
                } else if (implmentInterface(descriptor.getPropertyType(), Collection.class)) {// ?
                    // ===============begin======================
                    // 20151208getDeclaredFieldWithParent?type???
                    Field propertyType = getDeclaredFieldWithParent(clazz, propertyName);
                    if (propertyType == null) {
                        LOGGER.logMessage(LogLevel.WARN, "{}?{}", clazz.getName(), propertyName);
                        continue;
                    }
                    // ParameterizedType pt = (ParameterizedType) clazz
                    // .getDeclaredField(descriptor.getName())
                    // .getGenericType();
                    ParameterizedType pt = (ParameterizedType) propertyType.getGenericType();
                    // ===============end======================
                    Type[] actualTypeArguments = pt.getActualTypeArguments();
                    Collection<Object> collection = (Collection<Object>) getObjectInstance(type);
                    buildCollection(newPreName, collection, (Class) actualTypeArguments[0], context, null);
                    if (!collection.isEmpty()) {
                        BeanUtils.setProperty(object, descriptor.getName(), collection);
                        allPropertyNull = false;
                    }
                } else {// 
                    Object value = getObject(newPreName, null, descriptor.getPropertyType(), context, null);
                    if (value != null) {
                        BeanUtils.setProperty(object, descriptor.getName(), value);
                        allPropertyNull = false;
                    }
                }
            } catch (Exception e) {
                LOGGER.errorMessage("{0}", e, descriptor.getName());
            }
        }
    }
    if (allPropertyNull) {
        return null;
    }
    return object;
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private RuntimeException setField(InjectableField injectableField, Object createdObject, Object value) {
    Field field = injectableField.getField();
    Result<Object> result = adaptIfNecessary(value, field.getType(), field.getGenericType());
    if (result.wasSuccessful()) {
        boolean accessible = field.isAccessible();
        try {/*from w ww .  ja v a2s  .  c  om*/
            if (!accessible) {
                field.setAccessible(true);
            }
            field.set(createdObject, result.getValue());
        } catch (Exception e) {
            return new ModelClassException("Could not inject field due to reflection issues", e);
        } finally {
            if (!accessible) {
                field.setAccessible(false);
            }
        }
        return null;
    } else {
        return result.getThrowable();
    }
}