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.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

protected Class<?> getMapFieldType(Serializable instance, FieldManager fieldManager, Property property) {
    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];
        }//ww w . jav  a 2  s  .  com
    }
    return returnType;
}

From source file:org.dasein.persist.PersistentCache.java

protected void set(T target, Field field, Object value) throws PersistenceException {
    try {//from  ww  w . j  a v  a  2s  . co m
        ParameterizedType pt = null;
        field.setAccessible(true);
        if (field.getGenericType() instanceof ParameterizedType) {
            pt = (ParameterizedType) field.getGenericType();
        }
        field.set(target, mapValue(field.getName(), value, field.getType(), pt));
    } catch (IllegalArgumentException e) {
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    }
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

/**
 * Generate schema construct for given type
 *
 * @param javaType : Class to whcih need to generate Schema
 * @return : Generated QName/*  w  w  w  .j  av a 2 s.  c o  m*/
 */
protected QName generateSchema(Class<?> javaType) throws Exception {
    String name = getClassName(javaType);
    QName schemaTypeName = typeTable.getComplexSchemaType(name);
    if (schemaTypeName == null) {
        String simpleName = getSimpleClassName(javaType);

        String packageName = getQualifiedName(javaType.getPackage());
        String targetNameSpace = resolveSchemaNamespace(packageName);

        XmlSchema xmlSchema = getXmlSchema(targetNameSpace);
        String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace);
        if (targetNamespacePrefix == null) {
            targetNamespacePrefix = generatePrefix();
            targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix);
        }

        XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        XmlSchemaComplexContentExtension complexExtension = new XmlSchemaComplexContentExtension();

        XmlSchemaElement eltOuter = new XmlSchemaElement();
        schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix);
        eltOuter.setName(simpleName);
        eltOuter.setQName(schemaTypeName);

        Class<?> sup = javaType.getSuperclass();
        if ((sup != null) && (!"java.lang.Object".equals(sup.getName()))
                && (!"java.lang.Exception".equals(sup.getName()))
                && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2")
                && !getQualifiedName(sup.getPackage()).startsWith("java.util")) {
            String superClassName = sup.getName();
            String superclassname = getSimpleClassName(sup);
            String tgtNamespace;
            String tgtNamespacepfx;
            QName qName = typeTable.getSimpleSchemaTypeName(superClassName);
            if (qName != null) {
                tgtNamespace = qName.getNamespaceURI();
                tgtNamespacepfx = qName.getPrefix();
            } else {
                tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage()));
                tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace);
                QName superClassQname = generateSchema(sup);
                if (superClassQname != null) {
                    tgtNamespacepfx = superClassQname.getPrefix();
                    tgtNamespace = superClassQname.getNamespaceURI();
                }
            }
            if (tgtNamespacepfx == null) {
                tgtNamespacepfx = generatePrefix();
                targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx);
            }
            //if the parent class package name is differ from the child
            if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().contains(tgtNamespace)) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(tgtNamespace);
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).put(generatePrefix(), tgtNamespace);
            }

            QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx);
            complexExtension.setBaseTypeName(basetype);
            complexExtension.setParticle(sequence);
            XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent();
            contentModel.setContent(complexExtension);
            complexType.setContentModel(contentModel);

        } else {
            complexType.setParticle(sequence);
        }

        complexType.setName(simpleName);

        if (Modifier.isAbstract(javaType.getModifiers())) {
            complexType.setAbstract(true);
        }

        //            xmlSchema.getItems().add(eltOuter);
        xmlSchema.getElements().add(schemaTypeName, eltOuter);
        eltOuter.setSchemaTypeName(complexType.getQName());

        xmlSchema.getItems().add(complexType);
        xmlSchema.getSchemaTypes().add(schemaTypeName, complexType);

        // adding this type to the table
        typeTable.addComplexSchema(name, eltOuter.getQName());
        // adding this type's package to the table, to support inheritance.
        typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName());

        typeTable.addClassNameForQName(eltOuter.getQName(), name);

        BeanExcludeInfo beanExcludeInfo = null;
        if (service.getExcludeInfo() != null) {
            beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType));
        }

        // we need to get properties only for this bean. hence ignore the super
        // class properties
        BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass());

        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            String propertyName = property.getName();
            if (!property.getName().equals("class") && (property.getPropertyType() != null)) {
                if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) {
                    Type genericFieldType = null;
                    try {
                        Field field = javaType.getDeclaredField(propertyName);
                        genericFieldType = field.getGenericType();
                    } catch (Exception e) {
                        //log.info(e.getMessage());
                    }

                    if (genericFieldType instanceof ParameterizedType) {
                        ParameterizedType aType = (ParameterizedType) genericFieldType;
                        Type[] fieldArgTypes = aType.getActualTypeArguments();
                        try {
                            generateSchemaforGenericFields(xmlSchema, sequence, fieldArgTypes[0], propertyName);
                        } catch (Exception e) {
                            generateSchemaforFieldsandProperties(xmlSchema, sequence,
                                    property.getPropertyType(), propertyName,
                                    property.getPropertyType().isArray());
                        }
                    } else {
                        generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(),
                                propertyName, property.getPropertyType().isArray());
                    }
                }
            }
        }
    }
    return schemaTypeName;
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

@SuppressWarnings("unchecked")
private void setValue(final Field field, final Object bean, final Object value, final Object[] args)
        throws ReflectiveOperationException, SQLException, IllegalArgumentException, SecurityException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    final Class<?> fieldType = field.getType();
    if (fieldType == List.class) {
        if (value == null) {
            return;
        }// ww w. ja  v  a2s. com
        @SuppressWarnings("unchecked")
        List<Object> list = (List<Object>) Values.get(field.getName(), bean);
        if (list == null) {
            list = new ArrayList<Object>();
            //Values.set(field, bean, list);
            Values.set(field.getName(), bean, list);
        }
        final Class<?> elementType = (Class<?>) ((ParameterizedType) field.getGenericType())
                .getActualTypeArguments()[0];
        if (value instanceof ResultSet) {
            bindAll((ResultSet) value, elementType, list);
            Values.setParent(elementType, list, bean);
            return;
        }
        list.add(elementType.getDeclaredMethod("valueOf", Object[].class, Object.class).invoke(null, args,
                value));
        Values.setParent(elementType, list, value);
        return;
    }

    //Reflections.fieldValue(field, bean, value);
    Values.set(field.getName(), bean, value);
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules:/*from  www . jav a 2s. c o  m*/
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:org.flycraft.vkontakteapi.model.ParseUtils.java

/**
 * Parses object with follow rules:/* w  w w  . jav a 2  s.  c o  m*/
 * <p/>
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 * arrays of primitive types, {@link java.lang.String}s and {@link org.flycraft.vkontakteapi.model.VKApiModel}s,
 * list implementation line {@link org.flycraft.vkontakteapi.model.VKList}, {@link org.flycraft.vkontakteapi.model.VKAttachments.VKApiAttachment} or {@link org.flycraft.vkontakteapi.model.VKPhotoSizes},
 * {@link org.flycraft.vkontakteapi.model.VKApiModel}s.
 * <p/>
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T>    type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules://from   ww  w .  j  a  va 2 s  .co m
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:org.tdar.core.service.ReflectionService.java

/**
 * Find @link BulkImportField on a class.
 * /*  w w w.  j a  va  2s .c o  m*/
 * @param class2
 * @param stack
 * @param annotationToFind
 * @param runAs
 * @param runAsField
 * @param prefix
 * @return
 */
private LinkedHashSet<CellMetadata> handleClassAnnotations(Class<?> class2, Stack<List<Class<?>>> stack,
        Class<BulkImportField> annotationToFind, Class<?> runAs, Field runAsField, String prefix) {
    LinkedHashSet<CellMetadata> set = new LinkedHashSet<>();
    for (Field field : class2.getDeclaredFields()) {
        BulkImportField annotation = field.getAnnotation(annotationToFind);
        if (prefix == null) {
            prefix = "";
        }
        if (annotation != null) {
            String fieldPrefix = prefix;
            if (StringUtils.isNotBlank(annotation.key())) {
                fieldPrefix = CellMetadata.getDisplayLabel(MessageHelper.getInstance(), annotation.key());
            }

            Class<?> type = field.getType();
            if (Objects.equals(field, runAsField)) {
                type = runAs;
                logger.trace(" ** overriding type with {}", type.getSimpleName());
            }

            if (Collection.class.isAssignableFrom(type))
            // handle Collection private List<ResourceCreator> ...
            {
                ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
                Class<?> cls = (Class<?>) stringListType.getActualTypeArguments()[0];
                set.addAll(findBulkAnnotationsOnClass(cls, stack, fieldPrefix));
            }
            // handle Singleton private Person owner ...
            else if (Persistable.class.isAssignableFrom(type)) {
                set.addAll(findBulkAnnotationsOnClass(type, stack, fieldPrefix));
            }
            // handle more primative fields private String ...
            else {
                logger.trace("adding {} ({})", field, stack);
                if (!TdarConfiguration.getInstance().getCopyrightMandatory()
                        && Objects.equals(annotation.key(), InformationResource.COPYRIGHT_HOLDER)) {
                    continue;
                }

                if ((TdarConfiguration.getInstance().getLicenseEnabled() == false)
                        && (Objects.equals(field.getName(), "licenseType")
                                || Objects.equals(field.getName(), "licenseText"))) {
                    continue;
                }
                set.add(new CellMetadata(field, annotation, class2, stack, prefix));

                // set.add(field);
            }

        }
    }
    return set;
}

From source file:org.kuali.rice.krad.uif.util.CopyUtils.java

/**
 * Get a field reference for temporary use while deep cloning.
 * /*from  w ww.j  ava 2 s .c  om*/
 * <p>
 * Call {@link #recycle(CopyReference)} when done working with the reference.
 * </p>
 * 
 * @param source The source object.
 * @param target The target object.
 * @param field The field to use as the reference target.
 * 
 * @return A field reference for temporary use while deep cloning.
 */
private static <T> FieldReference<T> getFieldReference(Object source, Object target, Field field,
        CopyReference<T> pref) {
    @SuppressWarnings("unchecked")
    FieldReference<T> ref = RecycleUtils.getRecycledInstance(FieldReference.class);

    if (ref == null) {
        ref = new FieldReference<T>();
    }

    ref.source = source;
    ref.target = target;
    ref.field = field;

    DelayedCopy delayedCopy = field.getAnnotation(DelayedCopy.class);
    ref.delayAvailable = delayedCopy != null && (!delayedCopy.inherit() || pref.isDelayAvailable());

    Map<String, Type> pTypeVars = pref.getTypeVariables();

    if (pTypeVars != null && source != null) {
        Class<?> sourceType = source.getClass();
        Class<?> targetClass = pref.getTargetClass();
        Type targetType = ObjectPropertyUtils.findGenericType(sourceType, targetClass);
        if (targetType instanceof ParameterizedType) {
            ParameterizedType parameterizedTargetType = (ParameterizedType) targetType;
            Type[] params = parameterizedTargetType.getActualTypeArguments();
            for (int j = 0; j < params.length; j++) {
                if (params[j] instanceof TypeVariable<?>) {
                    Type pType = pTypeVars.get(targetClass.getTypeParameters()[j].getName());
                    ref.typeVariables.put(((TypeVariable<?>) params[j]).getName(), pType);
                }
            }
        }
    }

    Class<?> rawType = field.getType();
    Type genericType = field.getGenericType();
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        TypeVariable<?>[] typeParams = rawType.getTypeParameters();
        Type[] params = parameterizedType.getActualTypeArguments();
        assert params.length == typeParams.length;
        for (int i = 0; i < params.length; i++) {
            Type paramType = params[i];
            if (paramType instanceof TypeVariable<?>) {
                Type fType = ref.typeVariables.get(((TypeVariable<?>) paramType).getName());
                if (fType != null) {
                    paramType = fType;
                }
            }
            ref.typeVariables.put(typeParams[i].getName(), paramType);
        }
    }
    return ref;
}

From source file:de.bund.bva.pliscommon.ueberwachung.common.jmx.ServiceStatistikMBean.java

/**
 * Durchsucht eine Klasse nach Fehlerobjekten, die nicht null sind, oder Fehlercollections, die nicht leer
 * sind. Fehlerobjekten sind mit {link FachlicherFehler} annotiert.
 *
 * Durchsucht Oberklassen & untergeordnete Objektstrukturen ebenfalls rekursiv.
 *
 * @param result//from   ww w.  jav  a2s  .  c o m
 *            Das Objekt
 * @param clazz
 *            Die Klasse des Objekts durchsucht werden soll (optional). Kann leergelassen werden beim
 *            Start, kann aber genutzt werden um auf Oberklassen eines Objekts zu prfen.
 * @param tiefe
 *            tiefe Gibt die aktuelle Tiefe des Aufrufs an. Muss erhht werden wenn man die
 *            Klassenstruktur nach unten durchluft.
 * @return <code>true</code> wenn Fehler gefunden, ansonsten <code>false</code>
 */
boolean pruefeObjektAufFehler(final Object result, Class<?> clazz, int tiefe) {
    boolean fehlerGefunden = false;
    Class<?> clazzToScan = clazz;
    // Wenn keine Klasse bergeben, selber ermitteln
    if (clazzToScan == null) {
        clazzToScan = result.getClass();
    }

    // Wenn max. Tiefe erreicht, nicht weiter prfen
    if (tiefe > MAXTIEFE) {
        LOGISY.trace("Max. Tiefe erreicht, prfe nicht weiter auf fachliche Fehler");
        return false;
    }

    Field[] fields = clazzToScan.getDeclaredFields();

    LOGISY.trace("{} Analysiere Objekt {} (Klasse {}) {} Felder gefunden.", StringUtils.repeat("-", tiefe),
            result.toString(), clazzToScan.getSimpleName(), fields.length);

    for (Field field : fields) {
        if (!ClassUtils.isPrimitiveOrWrapper(field.getType()) && !field.getType().isEnum()) {
            LOGISY.trace("{} {}.{}, Type {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(),
                    field.getName(), field.getType().getSimpleName());
            field.setAccessible(true);
            try {
                // Prfe einzelne Klassenfelder (non-Collection) auf annotierten Typ und Vorhandensein
                if (!Collection.class.isAssignableFrom(field.getType())) {
                    if (field.get(result) != null) {
                        Object fieldObject = field.get(result);
                        if (fieldObject.getClass().isAnnotationPresent(FachlicherFehler.class)) {
                            // Fachliches Fehlerobjekt gefunden
                            return true;
                        }

                        // Wenn kein String, dann prfe rekursiv Objektstruktur
                        if (fieldObject.getClass() != String.class) {
                            fehlerGefunden = pruefeObjektAufFehler(fieldObject, null, tiefe + 1) ? true
                                    : fehlerGefunden;
                        }
                    }
                } else {
                    // Collection, prfen ob fachliche Fehlerliste
                    ParameterizedType type = (ParameterizedType) field.getGenericType();
                    Class<?> collectionTypeArgument = (Class<?>) type.getActualTypeArguments()[0];
                    if (collectionTypeArgument.isAnnotationPresent(FachlicherFehler.class)) {
                        // Ist Fehlerliste, prfen ob nicht leer
                        Collection<?> collection = (Collection<?>) field.get(result);
                        if (collection != null && !collection.isEmpty()) {
                            // Fachliche Fehler in Fehlerliste gefunden
                            return true;
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                // Nichts tun, Feld wird ignoriert
                LOGISY.debug("Feldzugriffsfehler: {}", e.getMessage());
            }
        }
    }

    // Die Klassen-Hierachie rekursiv nach oben prfen
    if (clazzToScan.getSuperclass() != null && !clazzToScan.getSuperclass().equals(Object.class)) {
        LOGISY.trace("{}> Climb up class hierarchy! Source {}, Target {}", StringUtils.repeat("-", tiefe),
                clazzToScan.getSimpleName(), clazzToScan.getSuperclass());
        fehlerGefunden =
                // Aufruf mit gleicher Tiefe, da Vererbung nach oben durchlaufen wird
                pruefeObjektAufFehler(result, clazzToScan.getSuperclass(), tiefe) ? true : fehlerGefunden;
    }

    return fehlerGefunden;
}