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.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Handle annotations made at the field level and add their data to the given metadata object.
  *//ww w  .  j  a va2 s  .  co  m
 * @param clazz the class to process.
  * @param metadata the metadata for the class.
 * @return <b>true</b> if any annotations are found.
 */
protected boolean processFieldLevelAnnotations(Class<?> clazz, DataObjectMetadataImpl metadata) {
    boolean fieldAnnotationsFound = false;
    boolean additionalClassAnnotationsFound = false;
    List<DataObjectAttribute> attributes = new ArrayList<DataObjectAttribute>();
    for (Field f : clazz.getDeclaredFields()) {
        boolean fieldAnnotationFound = false;
        String propertyName = f.getName();
        DataObjectAttributeImpl attr = (DataObjectAttributeImpl) metadata.getAttribute(propertyName);
        boolean existingAttribute = attr != null;
        if (!existingAttribute) {
            attr = new DataObjectAttributeImpl();
            attr.setName(propertyName);
            attr.setType(f.getType());
            DataType dataType = DataType.getDataTypeFromClass(f.getType());
            if (dataType == null) {
                dataType = DataType.STRING;
            }
            attr.setDataType(dataType);
            attr.setOwningType(metadata.getType());
        }
        Annotation[] fieldAnnotations = f.getDeclaredAnnotations();
        if (LOG.isDebugEnabled()) {
            LOG.debug(f.getDeclaringClass() + "." + f.getName() + " Field-level annotations: "
                    + Arrays.asList(fieldAnnotations));
        }
        for (Annotation a : fieldAnnotations) {
            // check if it's one we can handle then do something with it
            fieldAnnotationFound |= processAnnotationForAttribute(a, attr, metadata);
            if (!fieldAnnotationFound) {
                if (a instanceof BusinessKey) {
                    ArrayList<String> businessKeys = new ArrayList<String>(
                            metadata.getBusinessKeyAttributeNames());
                    businessKeys.add(f.getName());
                    metadata.setBusinessKeyAttributeNames(businessKeys);
                    // We are not altering the field definition, so dont set the flag
                    // fieldAnnotationFound = true;
                    additionalClassAnnotationsFound = true;
                    continue;
                }
                if (a instanceof Relationship) {
                    addDataObjectRelationship(metadata, f, (Relationship) a);

                    additionalClassAnnotationsFound = true;
                    continue;
                }
                if (a instanceof CollectionRelationship) {
                    addDataObjectCollection(metadata, f, (CollectionRelationship) a);

                    additionalClassAnnotationsFound = true;
                    continue;
                }
            }
        }
        if (fieldAnnotationFound) {
            attributes.add(attr);
            fieldAnnotationsFound = true;
        }
    }
    if (fieldAnnotationsFound) {
        metadata.setAttributes(attributes);
    }
    return fieldAnnotationsFound || additionalClassAnnotationsFound;
}

From source file:adalid.core.AbstractPersistentEntity.java

/**
 * @return the properties that are columns
 *//*w  w  w  .ja v  a 2 s.c om*/
//  @Override
public List<Property> getEntityTriggerColumnsList() {
    Class<?> baseTableClass = getBaseTableClass();
    if (baseTableClass == null) {
        return getPropertiesList();
    }
    if (isJoinedTable()) {
        return getJoinedPropertiesList();
    }
    List<Property> list = new ArrayList<>();
    Field field;
    Class<?> clazz;
    for (Property property : getPropertiesList()) {
        if (!property.isBaseField() && property.isInherited()) {
            field = property.getDeclaringField();
            clazz = field.getDeclaringClass();
            if (!baseTableClass.isAssignableFrom(clazz)) {
                continue;
            }
        }
        list.add(property);
    }
    return list;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object not part of a defined
 * table.//ww w. j  a  v a2s  .co  m
 *
 * @author vasu
 *
 * @param  cinfo the non-<code>null</code> class info for the POJO
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(ClassInfoImpl<T> cinfo, Field field) {
    this.clazz = cinfo.getObjectClass();
    this.cinfo = cinfo;
    this.tinfo = null;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.column = null;
    this.persisted = null;
    this.persister = null;
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = true; // keyspace suffixes are mandatory fields
    this.index = null; // we don't care about this for keyspace suffixes
    this.partitionKey = null; // we don't care about this for keyspace suffixes
    this.clusteringKey = null; // we don't care about this for keyspace suffixes
    this.typeKey = null; // we don't care about this for keyspace suffixes
    this.multiKeyType = null; // we don't care about this for keyspace suffixes
    this.definition = null; // we don't care about this for keyspace suffixes
    this.decoder = null; // we don't care about this for keyspace suffixes
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected MetadataObjectInfo<MetaProperty> loadCollectionProperty(MetaClassImpl metaClass, Field field) {
    Collection<RangeInitTask> tasks = new ArrayList<>();

    MetaPropertyImpl property = new MetaPropertyImpl(metaClass, field.getName());

    Class type = getFieldType(field);

    Range.Cardinality cardinality = getCardinality(field);
    boolean ordered = isOrdered(field);
    boolean mandatory = isMandatory(field);
    String inverseField = getInverseField(field);

    Map<String, Object> map = new HashMap<>();
    map.put("cardinality", cardinality);
    map.put("ordered", ordered);
    map.put("mandatory", mandatory);
    if (inverseField != null)
        map.put("inverseField", inverseField);

    property.setAnnotatedElement(field);
    property.setDeclaringClass(field.getDeclaringClass());
    property.setJavaType(field.getType());

    MetadataObjectInfo<Range> info = loadRange(property, type, map);
    Range range = info.getObject();/*from   www.  j  a v  a  2 s.  c om*/
    if (range != null) {
        ((AbstractRange) range).setCardinality(cardinality);
        ((AbstractRange) range).setOrdered(ordered);
        property.setRange(range);
        assignPropertyType(field, property, range);
        assignInverse(property, range, inverseField);
    }
    property.setMandatory(mandatory);

    tasks.addAll(info.getTasks());

    return new MetadataObjectInfo<>(property, tasks);
}

From source file:adalid.core.AbstractPersistentEntity.java

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

From source file:com.github.helenusdriver.driver.impl.ClassInfoImpl.java

/**
 * Gets the default value for the specified final field.
 *
 * @author paouelle// w w  w. j  a v a2s  .c  om
 *
 * @param  field the non-<code>null</code> final field for which to gets its
 *         default value
 * @return the corresponding default value
 * @throws IllegalArgumentException if the field is not a defined final field
 *         for the associated class or one of its super class up to and
 *         excluding the first one that is not annotated with the entity
 *         annotation
 */
public Object getDefaultValue(Field field) {
    final Object dflt = finalFields.getOrDefault(field, this);

    org.apache.commons.lang3.Validate.isTrue(dflt != this,
            "field '%s.%s' is not a valid final field for class '%s'", field.getDeclaringClass().getName(),
            field.getName(), clazz);
    return dflt;
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapParameters(List<APIParamModel> parameterList, Field fields[]) {
    for (Field field : fields) {
        APIParamModel paramModel = new APIParamModel();
        paramModel.setFieldName(field.getName());

        QueryParam queryParam = (QueryParam) field.getAnnotation(QueryParam.class);
        FormParam formParam = (FormParam) field.getAnnotation(FormParam.class);
        MatrixParam matrixParam = (MatrixParam) field.getAnnotation(MatrixParam.class);
        HeaderParam headerParam = (HeaderParam) field.getAnnotation(HeaderParam.class);
        CookieParam cookieParam = (CookieParam) field.getAnnotation(CookieParam.class);
        PathParam pathParam = (PathParam) field.getAnnotation(PathParam.class);
        BeanParam beanParam = (BeanParam) field.getAnnotation(BeanParam.class);

        if (queryParam != null) {
            paramModel.setParameterType(QueryParam.class.getSimpleName());
            paramModel.setParameterName(queryParam.value());
        }//from w  w  w  .  ja  v  a 2  s.  c o m
        if (formParam != null) {
            paramModel.setParameterType(FormParam.class.getSimpleName());
            paramModel.setParameterName(formParam.value());
        }
        if (matrixParam != null) {
            paramModel.setParameterType(MatrixParam.class.getSimpleName());
            paramModel.setParameterName(matrixParam.value());
        }
        if (pathParam != null) {
            paramModel.setParameterType(PathParam.class.getSimpleName());
            paramModel.setParameterName(pathParam.value());
        }
        if (headerParam != null) {
            paramModel.setParameterType(HeaderParam.class.getSimpleName());
            paramModel.setParameterName(headerParam.value());
        }
        if (cookieParam != null) {
            paramModel.setParameterType(CookieParam.class.getSimpleName());
            paramModel.setParameterName(cookieParam.value());
        }

        if (beanParam != null) {
            Class fieldClass = field.getDeclaringClass();
            mapParameters(parameterList, fieldClass.getDeclaredFields());
        }

        if (StringUtils.isNotBlank(paramModel.getParameterType())) {

            APIDescription aPIDescription = (APIDescription) field.getAnnotation(APIDescription.class);
            if (aPIDescription != null) {
                paramModel.setParameterDescription(aPIDescription.value());
            }

            ParameterRestrictions restrictions = (ParameterRestrictions) field
                    .getAnnotation(ParameterRestrictions.class);
            if (restrictions != null) {
                paramModel.setRestrictions(restrictions.value());
            }

            RequiredParam requiredParam = (RequiredParam) field.getAnnotation(RequiredParam.class);
            if (requiredParam != null) {
                paramModel.setRequired(true);
            }

            DefaultValue defaultValue = (DefaultValue) field.getAnnotation(DefaultValue.class);
            if (defaultValue != null) {
                paramModel.setDefaultValue(defaultValue.value());
            }

            parameterList.add(paramModel);
        }
    }
}

From source file:adalid.core.AbstractPersistentEntity.java

private List<Property> getSinglePropertiesList(Project project, List<Class<?>> subclasses) {
    List<Property> list = new ArrayList<>();
    Entity entity;//  ww  w.  j a v  a 2  s  .c  o m
    Class<?> type;
    Field field;
    Class<?> clazz;
    PersistentEntity pent;
    InheritanceMappingStrategy ims;
    for (Class<?> subclass : subclasses) {
        entity = project.getEntity(subclass);
        type = entity.getDataType();
        for (Property property : entity.getPropertiesList()) {
            field = property.getDeclaringField();
            clazz = field.getDeclaringClass();
            if (clazz.equals(type)) {
                list.add(property);
            }
        }
        pent = entity instanceof PersistentEntity ? (PersistentEntity) entity : null;
        ims = pent == null ? null : pent.getInheritanceMappingStrategy();
        if (InheritanceMappingStrategy.SINGLE_TABLE.equals(ims)) {
            list.addAll(getSinglePropertiesList(project, entity.getSubclassesList()));
        }
    }
    return list;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object as a column part of a
 * defined table.// w  w  w  . j  a  v  a 2  s  .c om
 *
 * @author vasu
 *
 * @param  tinfo the table info for the field
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(TableInfoImpl<T> tinfo, Field field) {
    this.clazz = tinfo.getObjectClass();
    this.cinfo = (ClassInfoImpl<T>) tinfo.getClassInfo();
    this.tinfo = tinfo;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.persisted = field.getAnnotation(Persisted.class);
    if (persisted != null) {
        org.apache.commons.lang3.Validate.isTrue(
                (persisted.as() != DataType.INFERRED) && !persisted.as().isCollection(),
                "@Persisted annotation cannot be of type '%s': %s.%s", persisted.as(), declaringClass.getName(),
                field.getName());
        this.persister = newPersister();
    } else {
        this.persister = null;
    }
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = field.getAnnotation(Mandatory.class) != null;
    final Map<String, Column> columns = ReflectionUtils.getAnnotationsByType(String.class, Column.class, field);
    final Map<String, Index> indexes = ReflectionUtils.getAnnotationsByType(String.class, Index.class, field);
    final Map<String, PartitionKey> partitionKeys = ReflectionUtils.getAnnotationsByType(String.class,
            PartitionKey.class, field);
    final Map<String, ClusteringKey> clusteringKeys = ReflectionUtils.getAnnotationsByType(String.class,
            ClusteringKey.class, field);
    final Map<String, TypeKey> typeKeys = ReflectionUtils.getAnnotationsByType(String.class, TypeKey.class,
            field);
    final boolean isInTable = tinfo.getTable() != null;

    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(!indexes.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!partitionKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!clusteringKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(!typeKeys.isEmpty() && columns.isEmpty()),
                "field must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    // Note: while searching for the matching table, uses the name from the
    // table annotation instead of the one returned by getName() as the later
    // might have been cleaned and hence would not match what was defined in
    // the POJO
    final String tname = isInTable ? tinfo.getTable().name() : Table.ALL;

    Column column = columns.get(tname);
    Index index = indexes.get(tname);
    PartitionKey partitionKey = partitionKeys.get(tname);
    ClusteringKey clusteringKey = clusteringKeys.get(tname);
    TypeKey typeKey = typeKeys.get(tname);

    if (column == null) { // fallback to special Table.ALL name
        column = columns.get(Table.ALL);
    }
    this.column = column;
    if (index == null) { // fallback to special Table.ALL name
        index = indexes.get(Table.ALL);
    }
    this.index = index;
    if (partitionKey == null) { // fallback to special Table.ALL name
        partitionKey = partitionKeys.get(Table.ALL);
    }
    this.partitionKey = partitionKey;
    if (clusteringKey == null) { // fallback to special Table.ALL name
        clusteringKey = clusteringKeys.get(Table.ALL);
    }
    this.clusteringKey = clusteringKey;
    if (typeKey == null) { // fallback to special Table.ALL name
        typeKey = typeKeys.get(Table.ALL);
    }
    this.typeKey = typeKey;
    // validate some UDT stuff
    if (!isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!isIndex(), "field cannot be annotated with @Index: %s.%s",
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isPartitionKey(),
                "field cannot be annotated with @PartitionKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isClusteringKey(),
                "field cannot be annotated with @ClusteringKey: %s.%s", declaringClass.getName(),
                field.getName());
        org.apache.commons.lang3.Validate.isTrue(!isTypeKey(), "field cannot be annotated with @TypeKey: %s.%s",
                declaringClass.getName(), field.getName());
    }
    if (isColumn()) {
        this.definition = DataTypeImpl.inferDataTypeFrom(field);
        this.decoder = definition.getDecoder(field, isMandatory() || isPartitionKey() || isClusteringKey());
        if (isInTable && ((clusteringKey != null) || (partitionKey != null))
                && (definition.getType() == DataType.SET)) {
            final Type type = field.getGenericType();

            if (type instanceof ParameterizedType) {
                final ParameterizedType ptype = (ParameterizedType) type;

                this.multiKeyType = ReflectionUtils.getRawClass(ptype.getActualTypeArguments()[0]); // sets will always have 1 argument
            } else {
                throw new IllegalArgumentException(
                        "unable to determine the element type of multi-field in table '" + tname + "': "
                                + declaringClass.getName() + "." + field.getName());
            }
        } else {
            this.multiKeyType = null;
        }
    } else {
        this.definition = null;
        this.decoder = null;
        this.multiKeyType = null;
    }
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
    // validate some stuff
    if (isInTable) {
        org.apache.commons.lang3.Validate.isTrue(!(isIndex() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @Index: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && isClusteringKey()),
                "field in table '%s' must not be annotated with @ClusteringKey if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isPartitionKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @PartitionKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isClusteringKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @ClusteringKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !isColumn()),
                "field in table '%s' must be annotated with @Column if it is annotated with @TypeKey: %s.%s",
                tname, declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && !String.class.equals(getType())),
                "field in table '%s' must be a String if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(!(isTypeKey() && isFinal()),
                "field in table '%s' must not be final if it is annotated with @TypeKey: %s.%s", tname,
                declaringClass.getName(), field.getName());
        org.apache.commons.lang3.Validate.isTrue(
                !(isTypeKey() && !(cinfo instanceof RootClassInfoImpl)
                        && !(cinfo instanceof TypeClassInfoImpl)),
                "field in table '%s' must not be annotated with @TypeKey if class is annotated with @Entity: %s.%s",
                tname, declaringClass.getName(), field.getName());
        if (isColumn() && definition.isCollection()) {
            org.apache.commons.lang3.Validate.isTrue(
                    !((isClusteringKey() || isPartitionKey()) && (multiKeyType == null)),
                    "field in table '%s' cannot be '%s' if it is annotated with @ClusteringKey or @PartitionKey: %s.%s",
                    tname, definition, declaringClass.getName(), field.getName());
        }
    }
}

From source file:com.github.helenusdriver.driver.impl.TableInfoImpl.java

/**
 * Gets a column field for the POJO in this table given its field name.
 *
 * @author paouelle/*from  w ww  . j a va 2 s . com*/
 *
 * @param  f the field to retrieve its column from this table
 * @return the corresponding column field or <code>null</code> if not defined
 */
public FieldInfoImpl<T> getColumnByField(Field f) {
    return fields.get(Pair.of(f.getName(), f.getDeclaringClass()));
}