Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:org.apache.cassandra.db.ScrubTest.java

/** The SecondaryIndex class is used for custom indexes so to avoid
 * making a public final field into a private field with getters
 * and setters, we resort to this hack in order to test it properly
 * since it can have two values which influence the scrubbing behavior.
 * @param comparator - the key comparator we want to test
 *//*from   w w w. j a  v a2  s  .  co  m*/
private void setKeyComparator(AbstractType<?> comparator) {
    try {
        Field keyComparator = SecondaryIndex.class.getDeclaredField("keyComparator");
        keyComparator.setAccessible(true);
        int modifiers = keyComparator.getModifiers();
        Field modifierField = keyComparator.getClass().getDeclaredField("modifiers");
        modifiers = modifiers & ~Modifier.FINAL;
        modifierField.setAccessible(true);
        modifierField.setInt(keyComparator, modifiers);

        keyComparator.set(null, comparator);
    } catch (Exception ex) {
        fail("Failed to change key comparator in secondary index : " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:adalid.core.Instance.java

private void finaliseFields() {
    String name;//from  w  w  w .j ava2 s  .  com
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    for (Field field : XS1.getFields(getClass(), Instance.class)) { // getClass().getDeclaredFields()
        field.setAccessible(true);
        logger.trace(field);
        name = field.getName();
        type = field.getType();
        if (!InstanceField.class.isAssignableFrom(type)) {
            continue;
        }
        modifiers = field.getModifiers();
        restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
        if (restricted) {
            continue;
        }
        String errmsg = "failed to initialize field \"" + field + "\" at " + this;
        try {
            o = field.get(this);
            if (o == null) {
                logger.debug(message(type, name, o, depth, round));
            } else if (o instanceof InstanceField) {
                finaliseInstanceField(field, (InstanceField) o);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            logger.error(errmsg, ThrowableUtils.getCause(ex));
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:edu.utah.further.fqe.impl.service.query.AggregationServiceImpl.java

/**
 * @param federatedQueryContext//from www. j  a va2 s  .c o  m
 * @return
 * @see edu.utah.further.fqe.api.service.query.AggregationService#generatedAggregatedResults(edu.utah.further.fqe.ds.api.domain.QueryContext)
 */
@Override
public synchronized AggregatedResults generateAggregatedResults(final QueryContext federatedQueryContext) {
    final QueryContext parent = qcService.findById(federatedQueryContext.getId());

    if (parent.getQueryType() == QueryType.COUNT_QUERY) {
        throw new ApplicationException("Data cannot be aggregated for count-only queries");
    }

    final List<QueryContext> children = qcService.findChildren(parent);

    if (children.size() < 1) {
        throw new ApplicationException("Federated QueryContext does not have any children");
    }

    final List<String> queryIds = new ArrayList<>();

    for (final QueryContext childContext : children) {
        if (childContext.isFailed()) {
            throw new ApplicationException(
                    "One or more queries failed, aggregated results cannot be generated");
        }

        queryIds.add(childContext.getExecutionId());
    }

    final Class<?> rootResultClass = resultDataService.getRootResultClass(queryIds);

    // Sanity check
    Validate.isTrue(PersistentEntity.class.isAssignableFrom(rootResultClass));

    final List<String> fields = new ArrayList<>();
    final Set<String> aggregationIncludedFields = categories.keySet();
    for (final Field field : rootResultClass.getDeclaredFields()) {
        // Only consider private and non-excluded fields
        if (Modifier.isPrivate(field.getModifiers()) && aggregationIncludedFields.contains(field.getName())) {
            fields.add(field.getName());
        }
    }

    final AggregatedResults aggregatedResults = new AggregatedResultsTo();

    // get all virtual ids for intersection
    final Map<Long, Set<Long>> commonToVirtualMap = identifierService.getCommonIdToVirtualIdMap(queryIds, true);
    final List<Long> idsInIntersection = CollectionUtil.newList();
    for (final Set<Long> virtuals : commonToVirtualMap.values()) {
        // Add the first virtual id, ignore all the others and make very big
        // assumption
        // that because they're the same person, they'll also have the same record
        // information
        idsInIntersection.add(virtuals.iterator().next());
    }

    if (queryIds.size() > 1) {
        // get all virtual ids for sum
        final List<Long> idsInSum = identifierService.getVirtualIdentifiers(queryIds);
        final AggregatedResult aggregatedSum = generateAggregatedResult(fields,
                rootResultClass.getCanonicalName(), queryIds, idsInSum, ResultType.SUM);
        aggregatedResults.addResult(aggregatedSum);

        final AggregatedResult aggregatedIntersection = generateAggregatedResult(fields,
                rootResultClass.getCanonicalName(), queryIds, idsInIntersection, ResultType.INTERSECTION);
        aggregatedResults.addResult(aggregatedIntersection);
    }

    // get all virtual ids for union
    final List<Long> idsInUnion = new ArrayList<>();
    idsInUnion.addAll(identifierService.getUnresolvedVirtualIdentifiers(queryIds));
    idsInUnion.addAll(idsInIntersection);

    final AggregatedResult aggregatedUnion = generateAggregatedResult(fields,
            rootResultClass.getCanonicalName(), queryIds, idsInUnion, ResultType.UNION);
    aggregatedResults.addResult(aggregatedUnion);

    aggregatedResults.setNumDataSources(queryIds.size());

    return aggregatedResults;
}

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java

private void set(Object obj, XmlParser.Node node) throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException {
    String attr = node.getAttribute("name");
    String name = "set" + attr.substring(0, 1).toUpperCase() + attr.substring(1);
    Object value = value(obj, node);
    Object[] arg = { value };/*from w  ww  .j  av  a 2 s.  c o m*/

    Class oClass = nodeClass(node);
    if (oClass != null)
        obj = null;
    else
        oClass = obj.getClass();

    Class[] vClass = { Object.class };
    if (value != null)
        vClass[0] = value.getClass();

    if (log.isDebugEnabled())
        log.debug(obj + "." + name + "(" + vClass[0] + " " + value + ")");

    // Try for trivial match
    try {
        Method set = oClass.getMethod(name, vClass);
        set.invoke(obj, arg);
        return;
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalAccessException e) {
        LogSupport.ignore(log, e);
    } catch (NoSuchMethodException e) {
        LogSupport.ignore(log, e);
    }

    // Try for native match
    try {
        Field type = vClass[0].getField("TYPE");
        vClass[0] = (Class) type.get(null);
        Method set = oClass.getMethod(name, vClass);
        set.invoke(obj, arg);
        return;
    } catch (NoSuchFieldException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalAccessException e) {
        LogSupport.ignore(log, e);
    } catch (NoSuchMethodException e) {
        LogSupport.ignore(log, e);
    }

    // Try a field
    try {
        Field field = oClass.getField(attr);
        if (Modifier.isPublic(field.getModifiers())) {
            field.set(obj, value);
            return;
        }
    } catch (NoSuchFieldException e) {
        LogSupport.ignore(log, e);
    }

    // Search for a match by trying all the set methods
    Method[] sets = oClass.getMethods();
    Method set = null;
    for (int s = 0; sets != null && s < sets.length; s++) {
        if (name.equals(sets[s].getName()) && sets[s].getParameterTypes().length == 1) {
            // lets try it
            try {
                set = sets[s];
                sets[s].invoke(obj, arg);
                return;
            } catch (IllegalArgumentException e) {
                LogSupport.ignore(log, e);
            } catch (IllegalAccessException e) {
                LogSupport.ignore(log, e);
            }
        }
    }

    // Try converting the arg to the last set found.
    if (set != null) {
        try {
            Class sClass = set.getParameterTypes()[0];
            if (sClass.isPrimitive()) {
                for (int t = 0; t < __primitives.length; t++) {
                    if (sClass.equals(__primitives[t])) {
                        sClass = __primitiveHolders[t];
                        break;
                    }
                }
            }
            Constructor cons = sClass.getConstructor(vClass);
            arg[0] = cons.newInstance(arg);
            set.invoke(obj, arg);
            return;
        } catch (NoSuchMethodException e) {
            LogSupport.ignore(log, e);
        } catch (IllegalAccessException e) {
            LogSupport.ignore(log, e);
        } catch (InstantiationException e) {
            LogSupport.ignore(log, e);
        }
    }

    // No Joy
    throw new NoSuchMethodException(oClass + "." + name + "(" + vClass[0] + ")");
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Checks all of the classes in the serialization scope that implement
 * TetradSerializable to make sure all of their fields are either themselves
 * (a) primitive, (b) TetradSerializable, or (c) assignable from types
 * designated as safely serializable by virtue of being included in the
 * safelySerializableTypes array (see), or are arrays whose lowest order
 * component types satisfy either (a), (b), or (c). Safely serializable
 * classes in the Java API currently include collections classes, plus
 * String and Class. Collections classes are included, since their types
 * will be syntactically checkable in JDK 1.5. String and Class are members
 * of a broader type of Class whose safely can by checked by making sure
 * there is no way to pass into them via constructor or method argument any
 * object that is not TetradSerializable or safely serializable. But it's
 * easy enough now to just make a list./*from ww w .  j  a  v  a2s.  c om*/
 *
 * @see #safelySerializableTypes
 */
public void checkNestingOfFields() {
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    boolean foundUnsafeField = false;

    for (Object aClass : classes) {
        Class clazz = (Class) aClass;

        if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
            continue;
        }

        Field[] fields = clazz.getDeclaredFields();

        FIELDS: for (Field field : fields) {
            //                System.out.println(field);

            if (Modifier.isTransient(field.getModifiers())) {
                continue;
            }

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            Class type = field.getType();

            while (type.isArray()) {
                type = type.getComponentType();
            }

            if (type.isPrimitive()) {
                continue;
            }

            if (type.isEnum()) {
                continue;
            }

            //                // Printing out Collections fields temporarily.
            //                if (Collection.class.isAssignableFrom(type)) {
            //                    System.out.println("COLLECTION FIELD: " + field);
            //                }
            //
            //                if (Map.class.isAssignableFrom(type)) {
            //                    System.out.println("MAP FIELD: " + field);
            //                }

            if (TetradSerializable.class.isAssignableFrom(type)
                    && !TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
                continue;
            }

            for (Class safelySerializableClass : safelySerializableTypes) {
                if (safelySerializableClass.isAssignableFrom(type)) {
                    continue FIELDS;
                }
            }

            // A reference in an inner class to the outer class.
            if (field.getName().equals("this$0")) {
                continue;
            }

            System.out.println("UNSAFE FIELD:" + field);
            foundUnsafeField = true;
        }
    }

    if (foundUnsafeField) {
        throw new RuntimeException("Unsafe serializable fields found. Please " + "fix immediately.");
    }
}

From source file:com.crowsofwar.gorecore.config.ConfigLoader.java

/**
 * Tries to load the field of the {@link #obj object} with the correct
 * {@link #data}./*ww w  .ja  v  a2s . c o  m*/
 * <p>
 * If the field isn't marked with @Load, does nothing. Otherwise, will
 * attempt to set the field's value (with reflection) to the data set in the
 * map.
 * 
 * @param field
 *            The field to load
 */
private <T> void loadField(Field field) {

    Class<?> cls = field.getDeclaringClass();
    Class<?> fieldType = field.getType();
    if (fieldType.isPrimitive())
        fieldType = ClassUtils.primitiveToWrapper(fieldType);

    try {

        if (field.getAnnotation(Load.class) != null) {

            if (Modifier.isStatic(field.getModifiers())) {

                GoreCore.LOGGER.log(Level.WARN,
                        "[ConfigLoader] Warning: Not recommended to mark static fields with @Load, may work out weirdly.");
                GoreCore.LOGGER.log(Level.WARN,
                        "This field is " + field.getDeclaringClass().getName() + "#" + field.getName());
                GoreCore.LOGGER.log(Level.WARN, "Use a singleton instead!");

            }

            // Should load this field

            HasCustomLoader loaderAnnot = fieldType.getAnnotation(HasCustomLoader.class);
            CustomLoaderSettings loaderInfo = loaderAnnot == null ? new CustomLoaderSettings()
                    : new CustomLoaderSettings(loaderAnnot);

            Object fromData = data.get(field.getName());
            Object setTo;

            boolean tryDefaultValue = fromData == null || ignoreConfigFile;

            if (tryDefaultValue) {

                // Nothing present- try to load default value

                if (field.get(obj) != null) {

                    setTo = field.get(obj);

                } else {
                    throw new ConfigurationException.UserMistake(
                            "No configured definition for " + field.getName() + ", no default value");
                }

            } else {

                // Value present in configuration.
                // Use the present value from map: fromData

                Class<Object> from = (Class<Object>) fromData.getClass();
                Class<?> to = fieldType;

                setTo = convert(fromData, to, field.getName());

            }
            usedValues.put(field.getName(), setTo);

            // If not a java class, probably custom; needs to NOT have the
            // '!!' in front
            if (!setTo.getClass().getName().startsWith("java")) {
                representer.addClassTag(setTo.getClass(), Tag.MAP);
                classTags.add(setTo.getClass());
            }

            // Try to apply custom loader, if necessary

            try {

                if (loaderInfo.hasCustomLoader())
                    loaderInfo.customLoaderClass.newInstance().load(null, setTo);

            } catch (InstantiationException | IllegalAccessException e) {

                throw new ConfigurationException.ReflectionException(
                        "Couldn't create a loader class of loader " + loaderInfo.customLoaderClass.getName(),
                        e);

            } catch (Exception e) {

                throw new ConfigurationException.Unexpected(
                        "An unexpected error occurred while using a custom object loader from config. Offending loader is: "
                                + loaderInfo.customLoaderClass,
                        e);

            }

            if (loaderInfo.loadFields)
                field.set(obj, setTo);

        }

    } catch (ConfigurationException e) {

        throw e;

    } catch (Exception e) {

        throw new ConfigurationException.Unexpected("An unexpected error occurred while loading field \""
                + field.getName() + "\" in class \"" + cls.getName() + "\"", e);

    }

}

From source file:com.px100systems.util.serialization.SerializationDefinition.java

private SerializationDefinition(Class<?> cls) {
    definitions.put(cls, this);

    if (cls.getName().startsWith("java"))
        throw new RuntimeException("System classes are not supported: " + cls.getSimpleName());

    try {//from www .j  a  v a2 s.c o  m
        constructor = cls.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName());
    }

    serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class);

    for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
                continue;

            FieldDefinition fd = new FieldDefinition();
            fd.name = field.getName();

            fd.type = field.getType();
            if (fd.type.isPrimitive())
                throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName());

            Calculated calc = field.getAnnotation(Calculated.class);

            if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class)
                    && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class)
                    && !fd.type.equals(String.class))
                if (fd.type.equals(List.class) || fd.type.equals(Set.class)) {
                    SerializedCollection sc = field.getAnnotation(SerializedCollection.class);
                    if (sc == null)
                        throw new RuntimeException(
                                cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection");

                    if (calc != null)
                        throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                + " cannot have a calculator because it is a collection");

                    fd.collectionType = sc.type();
                    fd.primitive = fd.collectionType.equals(Integer.class)
                            || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class)
                            || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class)
                            || fd.collectionType.equals(String.class);
                    if (!fd.primitive) {
                        if (cls.getName().startsWith("java"))
                            throw new RuntimeException(cls.getSimpleName() + "." + fd.name
                                    + ": system collection types are not supported: "
                                    + fd.collectionType.getSimpleName());

                        if (!definitions.containsKey(fd.collectionType))
                            new SerializationDefinition(fd.collectionType);
                    }
                } else {
                    if (cls.getName().startsWith("java"))
                        throw new RuntimeException(
                                "System classes are not supported: " + fd.type.getSimpleName());

                    if (!definitions.containsKey(fd.type))
                        new SerializationDefinition(fd.type);
                }
            else
                fd.primitive = true;

            try {
                fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter");
            }

            try {
                fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter");
            }

            if (calc != null)
                fd.calculator = new SpelExpressionParser().parseExpression(calc.value());

            fields.add(fd);
        }

        for (Method method : c.getDeclaredMethods())
            if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())
                    && method.getName().startsWith("get")
                    && method.isAnnotationPresent(SerializedGetter.class)) {
                FieldDefinition fd = new FieldDefinition();
                fd.name = method.getName().substring(3);
                fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1);
                fd.type = method.getReturnType();
                fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class)
                        || fd.type.equals(Double.class) || fd.type.equals(Boolean.class)
                        || fd.type.equals(Date.class) || fd.type.equals(String.class));

                if (!fd.primitive)
                    throw new RuntimeException("Not compact-serializable getter type: "
                            + (fd.type == null ? "void" : fd.type.getSimpleName()));

                fd.accessor = method;
                gettersOnly.add(fd);
            }
    }
}

From source file:com.gatf.executor.core.AcceptanceTestContext.java

private void initSoapContextAndHttpHeaders() throws Exception {
    Field[] declaredFields = HttpHeaders.class.getDeclaredFields();
    for (Field field : declaredFields) {
        if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) && field.getType().equals(String.class)) {
            httpHeaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());
        }//from w  w  w .ja v a 2s.c  o m
    }

    File file = null;
    if (gatfExecutorConfig.getWsdlLocFile() != null && !gatfExecutorConfig.getWsdlLocFile().trim().isEmpty())
        file = getResourceFile(gatfExecutorConfig.getWsdlLocFile());

    if (file != null) {
        Scanner s = new Scanner(file);
        s.useDelimiter("\n");
        List<String> list = new ArrayList<String>();
        while (s.hasNext()) {
            list.add(s.next().replace("\r", ""));
        }
        s.close();

        for (String wsdlLoc : list) {
            if (!wsdlLoc.trim().isEmpty()) {
                String[] wsdlLocParts = wsdlLoc.split(",");
                logger.info("Started Parsing WSDL location - " + wsdlLocParts[1]);
                Wsdl wsdl = Wsdl.parse(wsdlLocParts[1]);
                for (QName bindingName : wsdl.getBindings()) {
                    SoapBuilder builder = wsdl.getBuilder(bindingName);
                    for (SoapOperation operation : builder.getOperations()) {
                        String request = builder.buildInputMessage(operation);
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Document soapMessage = db.parse(new ByteArrayInputStream(request.getBytes()));

                        if (gatfExecutorConfig.isDistributedLoadTests()) {
                            soapStrMessages.put(wsdlLocParts[0] + operation.getOperationName(), request);
                        }

                        soapMessages.put(wsdlLocParts[0] + operation.getOperationName(), soapMessage);
                        if (operation.getSoapAction() != null) {
                            soapActions.put(wsdlLocParts[0] + operation.getOperationName(),
                                    operation.getSoapAction());
                        }
                        logger.info("Adding message for SOAP operation - " + operation.getOperationName());
                    }
                    soapEndpoints.put(wsdlLocParts[0], builder.getServiceUrls().get(0));
                    logger.info("Adding SOAP Service endpoint - " + builder.getServiceUrls().get(0));
                }
                logger.info("Done Parsing WSDL location - " + wsdlLocParts[1]);
            }
        }
    }
}

From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

public List<PersistentProperty> getPersistentProperties(PersistentEntity entity, MappingContext context,
        ClassMapping classMapping) {/*from ww  w .  j a v  a2s .  co m*/
    final List<PersistentProperty> persistentProperties = new ArrayList<PersistentProperty>();
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());

    // owners are the classes that own this class
    Collection embedded = cpf.getStaticPropertyValue(EMBEDDED, Collection.class);
    if (embedded == null)
        embedded = Collections.emptyList();

    Collection transients = cpf.getStaticPropertyValue(TRANSIENT, Collection.class);
    if (transients == null)
        transients = Collections.emptyList();

    // hasMany associations for defining one-to-many and many-to-many
    Map hasManyMap = getAssociationMap(cpf);
    // mappedBy for defining by which property an association is mapped
    Map mappedByMap = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
    if (mappedByMap == null)
        mappedByMap = Collections.emptyMap();
    // hasOne for declaring a one-to-one association with the foreign key in the child
    Map hasOneMap = cpf.getStaticPropertyValue(HAS_ONE, Map.class);
    if (hasOneMap == null)
        hasOneMap = Collections.emptyMap();

    for (PropertyDescriptor descriptor : cpf.getPropertyDescriptors()) {
        if (descriptor.getPropertyType() == null || descriptor.getPropertyType() == Object.class) {
            // indexed property
            continue;
        }
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
            // non-persistent getter or setter
            continue;
        }
        if (descriptor.getName().equals(VERSION) && !entity.isVersioned()) {
            continue;
        }

        Field field = cpf.getDeclaredField(descriptor.getName());
        if (field != null && java.lang.reflect.Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        final String propertyName = descriptor.getName();
        if (isExcludedProperty(propertyName, classMapping, transients))
            continue;
        Class<?> propertyType = descriptor.getPropertyType();
        Class currentPropType = propertyType;
        // establish if the property is a one-to-many
        // if it is a Set and there are relationships defined
        // and it is defined as persistent
        if (embedded.contains(propertyName)) {
            if (isCollectionType(currentPropType)) {
                Class relatedClassType = (Class) hasManyMap.get(propertyName);
                if (relatedClassType == null) {
                    Class javaClass = entity.getJavaClass();

                    Class genericClass = MappingUtils.getGenericTypeForProperty(javaClass, propertyName);

                    if (genericClass != null) {
                        relatedClassType = genericClass;
                    }
                }
                if (relatedClassType != null) {
                    if (propertyFactory.isSimpleType(relatedClassType)) {
                        Basic basicCollection = propertyFactory.createBasicCollection(entity, context,
                                descriptor);
                        persistentProperties.add(basicCollection);
                    } else {
                        EmbeddedCollection association = propertyFactory.createEmbeddedCollection(entity,
                                context, descriptor);

                        persistentProperties.add(association);
                        if (isPersistentEntity(relatedClassType)) {
                            association.setAssociatedEntity(
                                    getOrCreateAssociatedEntity(entity, context, relatedClassType));
                        } else {
                            PersistentEntity embeddedEntity = context.createEmbeddedEntity(relatedClassType);
                            embeddedEntity.initialize();
                            association.setAssociatedEntity(embeddedEntity);
                        }

                    }
                }
            } else {
                ToOne association = propertyFactory.createEmbedded(entity, context, descriptor);
                PersistentEntity associatedEntity = getOrCreateEmbeddedEntity(entity, context,
                        association.getType());
                association.setAssociatedEntity(associatedEntity);
                persistentProperties.add(association);
            }
        } else if (isCollectionType(currentPropType)) {
            final Association association = establishRelationshipForCollection(descriptor, entity, context,
                    hasManyMap, mappedByMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        }
        // otherwise if the type is a domain class establish relationship
        else if (isPersistentEntity(currentPropType)) {
            final ToOne association = establishDomainClassRelationship(entity, descriptor, context, hasOneMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        } else if (Enum.class.isAssignableFrom(currentPropType) || propertyFactory.isSimpleType(propertyType)) {
            persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
        } else if (MappingFactory.isCustomType(propertyType)) {
            persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
        }
    }
    return persistentProperties;
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private void deserializeClass(Class<?> instanceClass, Object instance) throws SerializationException,
        IllegalAccessException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
    Field[] serializableFields = SerializabilityUtil.applyFieldSerializationPolicy(instanceClass);

    for (Field declField : serializableFields) {
        assert (declField != null);

        Object value = deserializeValue(declField.getType());

        boolean isAccessible = declField.isAccessible();
        boolean needsAccessOverride = !isAccessible && !Modifier.isPublic(declField.getModifiers());
        if (needsAccessOverride) {
            // Override access restrictions
            declField.setAccessible(true);
        }//from   ww w .  j a  v a2  s  .co m

        declField.set(instance, value);
    }

    Class<?> superClass = instanceClass.getSuperclass();
    if (serializationPolicy.shouldDeserializeFields(superClass)) {
        deserializeImpl(SerializabilityUtil.hasCustomFieldSerializer(superClass), superClass, instance);
    }
}