Example usage for java.lang.reflect Field getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the field represented by this Field object.

Usage

From source file:adalid.core.AbstractArtifact.java

private boolean inherited() {
    if (_inherited == null) {
        Field declaringField = getDeclaringField();
        Artifact declaringArtifact = getDeclaringArtifact();
        Class<?> declaringFieldClass = declaringField.getDeclaringClass();
        Class<?> declaringFieldNamedClass = XS1.getNamedClass(declaringFieldClass);
        Class<?> declaringArtifactNamedClass = XS1.getNamedClass(declaringArtifact);
        String declaringFieldNamedClassSimpleName = declaringFieldNamedClass.getSimpleName();
        String declaringArtifactNamedClassSimpleName = declaringArtifactNamedClass.getSimpleName();
        _inherited = !declaringFieldNamedClassSimpleName.equals(declaringArtifactNamedClassSimpleName);
    }// w ww . java2 s .c om
    return _inherited;
}

From source file:ch.algotrader.cache.EntityHandler.java

private void processFieldsWithExisting(long entityId, Object obj, Object existingObj,
        List<EntityCacheSubKey> stack) {

    Validate.notNull(obj, "obj is null");
    Validate.notNull(existingObj, "existingObj is null");

    for (Field field : FieldUtil.getAllFields(obj.getClass())) {

        Object value = null;/* w w  w  . ja v  a 2s .c om*/
        try {
            value = field.get(obj);
        } catch (Exception e) {
            LOGGER.error("problem getting field", e);
        }

        // nothing to do on simple attributes
        if (FieldUtil.isSimpleAttribute(field) || value == null) {
            continue;
        }

        // if the object already existed but does not have the same reference replace it
        CacheResponse response = this.cacheManager.put(value, stack);

        try {
            if (response.getState() == CacheState.EXISTING) {
                Object existingValue = field.get(existingObj);
                if (response.getValue() != existingValue) {

                    field.set(existingObj, response.getValue());

                    EntityCacheKey cacheKey = new EntityCacheKey(field.getDeclaringClass(), entityId);
                    this.cacheManager.getEntityCache().attach(cacheKey, field.getName(), response.getValue());
                }
            } else if (response.getState() == CacheState.NEW) {
                Object existingValue = field.get(existingObj);
                if (existingValue != value) {

                    field.set(existingObj, value);

                    EntityCacheKey cacheKey = new EntityCacheKey(field.getDeclaringClass(), entityId);
                    this.cacheManager.getEntityCache().attach(cacheKey, field.getName(), value);
                }
            }
        } catch (IllegalArgumentException e) {
            LOGGER.error("problem update field value", e);
        } catch (IllegalAccessException e) {
            LOGGER.error("problem update field value", e);
        }
    }
}

From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Adds a collection relationship for a field to the metadata object.
 *
 * @param metadata the metadata for the class.
 * @param f the field to process.//  www  .ja va 2  s  .  com
 * @param a the collection relationship to add.
 */
protected void addDataObjectCollection(DataObjectMetadataImpl metadata, Field f, CollectionRelationship a) {
    List<DataObjectCollection> collections = new ArrayList<DataObjectCollection>(metadata.getCollections());
    DataObjectCollectionImpl collection = new DataObjectCollectionImpl();
    collection.setName(f.getName());

    if (!Collection.class.isAssignableFrom(f.getType())) {
        throw new IllegalArgumentException(
                "@CollectionRelationship annotations can only be on attributes of Collection type.  Field: "
                        + f.getDeclaringClass().getName() + "." + f.getName() + " (" + f.getType() + ")");
    }

    if (a.collectionElementClass().equals(Object.class)) { // Object is the default (and meaningless anyway)
        Type[] genericArgs = ((ParameterizedType) f.getGenericType()).getActualTypeArguments();
        if (genericArgs.length == 0) {
            throw new IllegalArgumentException(
                    "You can only leave off the collectionElementClass annotation on a @CollectionRelationship when the Collection type has been <typed>.  Field: "
                            + f.getDeclaringClass().getName() + "." + f.getName() + " (" + f.getType() + ")");
        }
        collection.setRelatedType((Class<?>) genericArgs[0]);
    } else {
        collection.setRelatedType(a.collectionElementClass());
    }

    List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>(
            a.attributeRelationships().length);
    for (AttributeRelationship rel : a.attributeRelationships()) {
        attributeRelationships.add(
                new DataObjectAttributeRelationshipImpl(rel.parentAttributeName(), rel.childAttributeName()));
    }
    collection.setAttributeRelationships(attributeRelationships);

    collection.setReadOnly(false);
    collection.setSavedWithParent(false);
    collection.setDeletedWithParent(false);
    collection.setLoadedAtParentLoadTime(true);
    collection.setLoadedDynamicallyUponUse(false);
    List<DataObjectCollectionSortAttribute> sortAttributes = new ArrayList<DataObjectCollectionSortAttribute>(
            a.sortAttributes().length);
    for (CollectionSortAttribute csa : a.sortAttributes()) {
        sortAttributes.add(new DataObjectCollectionSortAttributeImpl(csa.value(), csa.sortDirection()));
    }
    collection.setDefaultCollectionOrderingAttributeNames(sortAttributes);

    collection.setIndirectCollection(a.indirectCollection());
    collection.setMinItemsInCollection(a.minItemsInCollection());
    collection.setMaxItemsInCollection(a.maxItemsInCollection());
    if (StringUtils.isNotBlank(a.label())) {
        collection.setLabel(a.label());
    }
    if (StringUtils.isNotBlank(a.elementLabel())) {
        collection.setLabel(a.elementLabel());
    }

    collections.add(collection);
    metadata.setCollections(collections);
}

From source file:org.apache.camel.dataformat.bindy.BindyCsvFactory.java

public void bind(List<String> tokens, Map<String, Object> model, int line) throws Exception {

    int pos = 1;/*from w ww  .java 2s  . c  om*/
    int counterMandatoryFields = 0;

    for (String data : tokens) {

        // Get DataField from model
        DataField dataField = dataFields.get(pos);
        ObjectHelper.notNull(dataField,
                "No position " + pos + " defined for the field : " + data + ", line : " + line);

        if (dataField.trim()) {
            data = data.trim();
        }

        if (dataField.required()) {
            // Increment counter of mandatory fields
            ++counterMandatoryFields;

            // Check if content of the field is empty
            // This is not possible for mandatory fields
            if (data.equals("")) {
                throw new IllegalArgumentException("The mandatory field defined at the position " + pos
                        + " is empty for the line : " + line);
            }
        }

        // Get Field to be setted
        Field field = annotedFields.get(pos);
        field.setAccessible(true);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Pos : " + pos + ", Data : " + data + ", Field type : " + field.getType());
        }

        Format<?> format;

        // Get pattern defined for the field
        String pattern = dataField.pattern();

        // Create format object to format the field
        format = FormatFactory.getFormat(field.getType(), pattern, getLocale(), dataField.precision());

        // field object to be set
        Object modelField = model.get(field.getDeclaringClass().getName());

        // format the data received
        Object value = null;

        if (!data.equals("")) {
            try {
                value = format.parse(data);
            } catch (FormatException ie) {
                throw new IllegalArgumentException(ie.getMessage() + ", position : " + pos + ", line : " + line,
                        ie);
            } catch (Exception e) {
                throw new IllegalArgumentException("Parsing error detected for field defined at the position : "
                        + pos + ", line : " + line, e);
            }
        } else {
            value = getDefaultValueForPrimitive(field.getType());
        }

        field.set(modelField, value);

        ++pos;

    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Counter mandatory fields : " + counterMandatoryFields);
    }

    if (pos < totalFields) {
        throw new IllegalArgumentException("Some fields are missing (optional or mandatory), line : " + line);
    }

    if (counterMandatoryFields < numberMandatoryFields) {
        throw new IllegalArgumentException("Some mandatory fields are missing, line : " + line);
    }

}

From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java

private String getKeyByConvention(Field field, String prefix,
        org.apache.commons.configuration.Configuration config) {

    Set<String> conventions = new HashSet<String>();
    conventions.add(field.getName());/*from  w  ww  .j a v a  2  s .  c o m*/
    conventions.add(Strings.camelCaseToSymbolSeparated(field.getName(), "."));
    conventions.add(Strings.camelCaseToSymbolSeparated(field.getName(), "_"));
    conventions.add(field.getName().toLowerCase());
    conventions.add(field.getName().toUpperCase());

    int matches = 0;
    String key = field.getName();
    for (String convention : conventions) {
        if (config.containsKey(prefix + convention)) {
            key = convention;
            matches++;
        }
    }

    if (matches == 0) {
        logger.debug(bundle.getString("configuration-key-not-found", key, conventions));
    } else if (matches > 1) {
        throw new ConfigurationException(
                bundle.getString("ambiguous-key", field.getName(), field.getDeclaringClass()));
    }

    return key;
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Build the FieldInfo for a Field.//from  w w  w  .j av  a2s  .  co  m
 * 
 * @param classInfo
 *            the ClassInfo to check if this field already exists
 * @param field
 *            the Field to describe
 * @return the ClassInfo containing the FieldInfo build
 */
private void buildFieldInfo(final ClassInfo classInfo, final Field field) {
    if (classInfo == null) {
        String message = "Argument classInfo must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    if (field == null) {
        String message = "Argument field must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    String fieldName = javaNaming.extractFieldNameFromField(field);
    FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName);
    if (fieldInfo == null) {
        fieldInfo = createFieldInfo(fieldName);
        classInfo.addFieldInfo(fieldInfo);
        fieldInfo.setParentClassInfo(classInfo);
    }
    JaxbFieldNature jaxbFieldNature = new JaxbFieldNature(fieldInfo);
    jaxbFieldNature.setField(field);
    Class<?> fieldType = field.getDeclaringClass();
    if (fieldType.isArray() || fieldType.isAssignableFrom(Collection.class)) {
        jaxbFieldNature.setMultivalued(true);
    }
    jaxbFieldNature.setGenericType(field.getGenericType());
    fieldAnnotationProcessingService.processAnnotations(jaxbFieldNature, field.getAnnotations());
}

From source file:org.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

private void processFields(Field[] fields, Object realInstance) {

    for (Field field : fields) {
        if (annotationPresent(field, WithRealmService.class)) {
            field.setAccessible(true);/*from   w w w  .  j ava 2 s. com*/
            Annotation annotation = field.getAnnotation(WithRealmService.class);
            WithRealmService withRealmService = (WithRealmService) annotation;
            try {
                RealmService realmService = createRealmService(withRealmService, true);
                field.set(realInstance, realmService);
                IdentityTenantUtil.setRealmService(realmService);
                CarbonCoreDataHolder.getInstance().setRealmService(realmService);
            } catch (IllegalAccessException e) {
                log.error("Error in setting field value: " + field.getName() + ", Class: "
                        + field.getDeclaringClass(), e);
            } catch (UserStoreException e) {
                log.error("Error in setting user store value: " + field.getName() + ", Class: "
                        + field.getDeclaringClass(), e);
            }

        }
        if (annotationPresent(field, InjectMicroservicePort.class)) {
            MicroserviceServer microserviceServer = microserviceServerMap.get(realInstance);
            if (microserviceServer != null) {
                field.setAccessible(true);
                try {
                    field.set(realInstance, microserviceServer.getPort());
                } catch (IllegalAccessException e) {
                    log.error("Error in setting micro-service port: " + field.getName() + ", Class: "
                            + field.getDeclaringClass(), e);
                }
            }
        }
    }
}

From source file:org.structr.module.JarConfigurationProvider.java

@Override
public void registerEntityType(final Class type) {

    // moved here from scanEntity, no reason to have this in a separate
    // method requiring two different calls instead of one
    String simpleName = type.getSimpleName();
    String fullName = type.getName();

    if (AbstractNode.class.isAssignableFrom(type)) {
        nodeEntityClassCache.put(simpleName, type);
        nodeEntityPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));
        globalPropertyViewMap.remove(type.getName());
    }/*from   w ww. j  a  va  2s  .  c  o m*/

    if (AbstractRelationship.class.isAssignableFrom(type)) {

        relationshipEntityClassCache.put(simpleName, type);
        relationshipPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));
        globalPropertyViewMap.remove(type.getName());
    }

    for (Class interfaceClass : type.getInterfaces()) {

        String interfaceName = interfaceClass.getSimpleName();
        Set<Class> classesForInterface = interfaceCache.get(interfaceName);

        if (classesForInterface == null) {

            classesForInterface = new LinkedHashSet<>();

            interfaceCache.put(interfaceName, classesForInterface);

        }

        classesForInterface.add(type);

    }

    try {

        Map<Field, PropertyKey> allProperties = getFieldValuesOfType(PropertyKey.class, type);
        Map<Field, View> views = getFieldValuesOfType(View.class, type);

        for (Map.Entry<Field, PropertyKey> entry : allProperties.entrySet()) {

            PropertyKey propertyKey = entry.getValue();
            Field field = entry.getKey();
            Class declaringClass = field.getDeclaringClass();

            if (declaringClass != null) {

                propertyKey.setDeclaringClass(declaringClass);
                registerProperty(declaringClass, propertyKey);

            }

            registerProperty(type, propertyKey);
        }

        for (Map.Entry<Field, View> entry : views.entrySet()) {

            Field field = entry.getKey();
            View view = entry.getValue();

            for (PropertyKey propertyKey : view.properties()) {

                // register field in view for entity class and declaring superclass
                registerPropertySet(field.getDeclaringClass(), view.name(), propertyKey);
                registerPropertySet(type, view.name(), propertyKey);
            }
        }

    } catch (Throwable t) {
        logger.log(Level.SEVERE, "Unable to register type {0}: {1}", new Object[] { type, t.getMessage() });
        t.printStackTrace();
    }

    Map<String, Method> typeMethods = exportedMethodMap.get(type.getName());
    if (typeMethods == null) {
        typeMethods = new HashMap<>();
        exportedMethodMap.put(type.getName(), typeMethods);
    }

    typeMethods.putAll(getAnnotatedMethods(type, Export.class));

    // extract interfaces for later use
    getInterfacesForType(type);
}

From source file:adalid.core.AbstractPersistentEntity.java

private List<Property> getNonInheritedPropertiesList() {
    List<Property> list = new ArrayList<>();
    Class<?> type = getDataType();
    Field field;
    Class<?> clazz;/*from   w  ww  . j a  v  a 2 s  .c o m*/
    for (Property property : getPropertiesList()) {
        field = property.getDeclaringField();
        clazz = field.getDeclaringClass();
        if (clazz.equals(type)) {
            list.add(property);
        }
    }
    return list;
}

From source file:adalid.core.AbstractPersistentEntity.java

/**
 * @return the insertable rows//from  ww  w  .j av  a  2  s  .  c  o  m
 */
//  @Override
public List<Instance> getInsertableRowsList() {
    List<Instance> list = new ArrayList<>();
    Class<?> type = getDataType();
    Field field;
    Class<?> clazz;
    for (Instance instance : getInstancesList()) {
        field = instance.getDeclaringField();
        if (isJoinedTable()) {
            clazz = field.getDeclaringClass();
            if (!clazz.equals(type)) {
                continue;
            }
        }
        list.add(instance);
    }
    return list;
}