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:org.polymap.model2.engine.InstanceBuilder.java

protected Iterable<PropertyConcernBase> fieldConcerns(final Field field, final PropertyBase prop)
        throws Exception {
    List<Class> concernTypes = concerns.get(field, new Loader<Field, List<Class>>() {
        public List<Class> load(Field key) {
            List<Class> result = new ArrayList();
            // Class concerns
            Concerns ca = field.getDeclaringClass().getAnnotation(Concerns.class);
            if (ca != null) {
                result.addAll(Arrays.asList(ca.value()));
            }//from w w w. j  ava  2 s.  c  om
            // Field concerns
            Concerns fa = field.getAnnotation(Concerns.class);
            if (fa != null) {
                for (Class<? extends PropertyConcernBase> concern : fa.value()) {
                    result.add(concern);
                }
            }
            return result;
        }
    });

    return Iterables.transform(concernTypes, new Function<Class, PropertyConcernBase>() {
        public PropertyConcernBase apply(Class concernType) {
            try {
                // early check concern type
                if (Property.class.isAssignableFrom(field.getType())
                        && !PropertyConcern.class.isAssignableFrom(concernType)) {
                    throw new ModelRuntimeException("Concerns of Property have to extend PropertyConcern: "
                            + concernType.getName() + " @ " + field.getName());
                } else if (CollectionProperty.class.isAssignableFrom(field.getType())
                        && !CollectionPropertyConcern.class.isAssignableFrom(concernType)) {
                    throw new ModelRuntimeException(
                            "Concerns of CollectionProperty have to extend CollectionPropertyConcern: "
                                    + concernType.getName() + " @ " + field.getName());
                } else if (Association.class.isAssignableFrom(field.getType())
                        && !AssociationConcern.class.isAssignableFrom(concernType)) {
                    throw new ModelRuntimeException(
                            "Concerns of Association have to extend AssociationConcern: "
                                    + concernType.getName() + " @ " + field.getName());
                }

                // create concern
                PropertyConcernBase concern = (PropertyConcernBase) concernType.newInstance();
                concernContextField.set(concern, context);
                concernDelegateField.set(concern, prop);

                return concern;
            } catch (ModelRuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new ModelRuntimeException("Error while initializing concern: " + concernType + " ("
                        + e.getLocalizedMessage() + ")", e);
            }
        }
    });
}

From source file:org.structr.core.EntityContext.java

public static void scanEntity(Object entity) {

    Map<Field, PropertyKey> allProperties = getFieldValuesOfType(PropertyKey.class, entity);
    Map<Field, View> views = getFieldValuesOfType(View.class, entity);
    Class entityType = entity.getClass();

    for (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);

        }/*from w  ww.  ja va2  s . c  om*/

        registerProperty(entityType, propertyKey);
    }

    for (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(entityType, view.name(), propertyKey);
        }
    }
}

From source file:richtercloud.reflection.form.builder.fieldhandler.MappingFieldHandler.java

/**
 * Must never return {@code null}, otherwise {@link #handle(java.lang.reflect.Field, java.lang.Object, richtercloud.reflection.form.builder.fieldhandler.FieldUpdateListener, richtercloud.reflection.form.builder.ReflectionFormBuilder) } throws {@link IllegalArgumentException}.
 * @param field/*  ww  w  .  jav  a  2  s. c o  m*/
 * @param instance
 * @param updateListener
 * @param reflectionFormBuilder
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws FieldHandlingException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
protected Pair<JComponent, ComponentHandler<?>> handle0(final Field field, final Object instance,
        FieldUpdateListener<E> updateListener, R reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    JComponent retValue;
    T fieldValue = (T) field.get(instance);
    String fieldName = field.getName();
    Class<?> declaringClass = field.getDeclaringClass();

    FieldHandler fieldHandler = null;
    //can't have a generic type because it requires R to be passed down
    //the call hierarchy which requires to redesign the whole mapping
    //factory hierarchy which is extremely difficult due to entangled
    //generics like FieldHandler<T, FieldUpdateEvent<T>, ...>
    if (field.getType().isPrimitive()) {
        fieldHandler = primitiveMapping.get(field.getType());
    } else {
        // check exact type match
        fieldHandler = retrieveFieldHandler(field.getGenericType(), classMapping);
    }
    ComponentHandler<?> componentResettable;
    if (fieldHandler == null) {
        return null;
    }
    retValue = fieldHandler.handle(field, instance, new FieldUpdateListener<FieldUpdateEvent<?>>() {
        @Override
        public void onUpdate(FieldUpdateEvent<?> event) {
            try {
                field.set(instance, event.getNewValue());
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new RuntimeException(ex);
            }
        }
    }, reflectionFormBuilder);
    componentResettable = fieldHandler;
    return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, componentResettable);
}

From source file:org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldBase.java

/**
 * Build a String representation of given arguments.
 *///from ww w  .  j  a  v a2  s .com
protected String buildErrorGetMsg(Object obj, Field aField) {
    String eol = SystemUtils.LINE_SEPARATOR;
    StringBuffer buf = new StringBuffer();
    buf.append(eol + "[try to read from source object")
            .append(eol + "source obj class: " + (obj != null ? obj.getClass().getName() : null))
            .append(eol + "target field name: " + (aField != null ? aField.getName() : null))
            .append(eol + "target field type: " + (aField != null ? aField.getType() : null))
            .append(eol + "target field declared in: "
                    + (aField != null ? aField.getDeclaringClass().getName() : null))
            .append(eol + "]");
    return buf.toString();
}

From source file:org.unitils.inject.InjectModule.java

/**
 * Given the errorDescription, returns a situated error message, i.e. specifying the annotated field and the
 * annotation type that was used.//from   w  ww  .  j  a  v a 2s . co  m
 *
 * @param annotationClass  The injection annotation, not null
 * @param annotatedField   The annotated field, not null
 * @param errorDescription A custom description, not null
 * @return A situated error message
 */
protected String getSituatedErrorMessage(Class<? extends Annotation> annotationClass, Field annotatedField,
        String errorDescription) {
    return "Error while processing @" + annotationClass.getSimpleName() + " annotation on field "
            + annotatedField.getName() + " of class " + annotatedField.getDeclaringClass().getSimpleName()
            + ": " + errorDescription;
}

From source file:org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldBase.java

/**
 * Build a String representation of given arguments.
 *//*from   w ww.j  a v  a2  s.  co m*/
protected String buildErrorSetMsg(Object obj, Object value, Field aField) {
    String eol = SystemUtils.LINE_SEPARATOR;
    StringBuffer buf = new StringBuffer();
    buf.append(eol + "[try to set 'object value' in 'target object'")
            .append(eol + "target obj class: " + (obj != null ? obj.getClass().getName() : null))
            .append(eol + "target field name: " + (aField != null ? aField.getName() : null))
            .append(eol + "target field type: " + (aField != null ? aField.getType() : null))
            .append(eol + "target field declared in: "
                    + (aField != null ? aField.getDeclaringClass().getName() : null))
            .append(eol + "object value class: " + (value != null ? value.getClass().getName() : null))
            .append(eol + "object value: " + (value != null ? value : null)).append(eol + "]");
    return buf.toString();
}

From source file:org.projectforge.framework.configuration.ConfigXml.java

public String exportConfiguration() {
    final XmlObjectWriter writer = new XmlObjectWriter() {
        @Override//from   w  w  w .ja  va  2  s.  c om
        protected boolean ignoreField(final Object obj, final Field field) {
            if (field.getDeclaringClass().isAssignableFrom(ConfigXml.class) == true
                    && StringHelper.isIn(field.getName(), "expireTime", "timeOfLastRefresh") == true) {
                return true;
            }
            return super.ignoreField(obj, field);
        }

        /**
         * @see org.projectforge.framework.xstream.XmlObjectWriter#writeField(java.lang.reflect.Field, java.lang.Object,
         *      java.lang.Object, org.projectforge.framework.xstream.XmlField, org.dom4j.Element)
         */
        @Override
        protected void writeField(final Field field, final Object obj, final Object fieldValue,
                final XmlField annotation, final Element element) {
            if (field != null) {
                if (field.isAnnotationPresent(ConfigXmlSecretField.class) == true) {
                    super.writeField(field, obj, SECRET_PROPERTY_STRING, annotation, element);
                    return;
                }
            }
            super.writeField(field, obj, fieldValue, annotation, element);
        }
    };
    final String xml = writer.writeToXml(this, true);
    return XmlHelper.XML_HEADER + xml;
}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected boolean setterExists(Field field) {
    String name = "set" + StringUtils.capitalize(field.getName());
    Method[] methods = field.getDeclaringClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(name))
            return true;
    }/*  w w  w .j  a v  a  2  s .  c  o m*/
    return false;
}

From source file:info.archinnov.achilles.helper.EntityIntrospector.java

public Method findSetter(Class<?> beanClass, Field field) {
    log.debug("Find setter for field {} in class {}", field.getName(), beanClass.getCanonicalName());

    String fieldName = field.getName();

    try {//from  ww  w.  j  a v  a 2s.  c o m
        String setter = this.deriveSetterName(field);
        Method setterMethod = beanClass.getMethod(setter, field.getType());

        if (!setterMethod.getReturnType().toString().equals("void")) {
            throw new AchillesBeanMappingException("The setter for field '" + fieldName + "' of type '"
                    + field.getDeclaringClass().getCanonicalName()
                    + "' does not return correct type or does not have the correct parameter");
        }

        log.trace("Derived setter method : {}", setterMethod.getName());
        return setterMethod;

    } catch (NoSuchMethodException e) {
        throw new AchillesBeanMappingException("The setter for field '" + fieldName + "' of type '"
                + field.getDeclaringClass().getCanonicalName() + "' does not exist or is incorrect");
    }
}

From source file:org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldBase.java

protected List getFieldGraph(boolean makeAccessible) {
    List result = new ArrayList();
    String[] fields = StringUtils.split(getName(), PATH_TOKEN);
    Field fld = null;
    for (int i = 0; i < fields.length; i++) {
        String fieldName = fields[i];
        try {//ww w  .  jav  a2s .  c  o  m
            if (fld == null) {
                fld = getFieldRecursive(rootObjectType, fieldName);
            } else {
                fld = getFieldRecursive(fld.getType(), fieldName);
            }
            if (makeAccessible) {
                fld.setAccessible(true);
            }
        } catch (NoSuchFieldException e) {
            throw new MetadataException("Can't find member '" + fieldName + "' in class "
                    + (fld != null ? fld.getDeclaringClass() : rootObjectType), e);
        }
        result.add(fld);
    }
    return result;
}