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:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

private <K, V> Pair<Class<K>, Class<V>> determineMapGenericTypes(Field field) {
    log.trace("Determine generic types for field Map<K,V> {} of entity class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());

    Type genericType = field.getGenericType();
    ParameterizedType pt = (ParameterizedType) genericType;
    Type[] actualTypeArguments = pt.getActualTypeArguments();

    Class<K> keyClass = getClassFromType(actualTypeArguments[0]);
    Class<V> valueClass = getClassFromType(actualTypeArguments[1]);

    return Pair.create(keyClass, valueClass);
}

From source file:org.jmingo.document.id.IdFieldGenerator.java

private void setValue(Object pojo, Field field, Object val, String strategy) {
    try {// ww w.j  a  v a  2 s  .c  o  m
        if (!instanceOf(val.getClass(), field.getType())) {
            Function transformer = transformers.get(val.getClass(), field.getType());
            if (transformer == null) {
                throw new IdGenerationException(format(INCOMPATIBLE_TYPES, val, val.getClass(), field.getName(),
                        field.getType(), field.getDeclaringClass(), strategy));
            }
            val = transformer.apply(val);
        }
        field.set(pojo, val);
    } catch (IllegalAccessException e) {
        throw new IdGenerationException(e);
    }
}

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

/**
 * Tries to load the field of the {@link #obj object} with the correct
 * {@link #data}.//from ww w .  j av a  2  s  . 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.github.helenusdriver.driver.impl.DataTypeImpl.java

/**
 * Infers the data type from the specified field.
 *
 * @author paouelle/* w  w  w. j  a  va  2 s  . c  o  m*/
 *
 * @param  field the field from which to infer the data type
 * @return a non-<code>null</code> data type definition
 * @throws NullPointerException if <code>field</code> is <code>null</code>
 * @throws IllegalArgumentException if the data type cannot be inferred from
 *         the field or it is persisted but the persister cannot be instantiate
 */
public static Definition inferDataTypeFrom(Field field) {
    org.apache.commons.lang3.Validate.notNull(field, "invalid null field");
    final Persisted persisted = field.getAnnotation(Persisted.class);

    if (persisted == null) {
        final Column.Data cdata = field.getAnnotation(Column.Data.class);

        if (cdata != null) {
            final DataType type = cdata.type();
            final List<CQLDataType> atypes = new ArrayList<>(Arrays.asList(cdata.arguments()));

            if (type != DataType.INFERRED) {
                org.apache.commons.lang3.Validate.isTrue(!(atypes.size() < type.NUM_ARGUMENTS),
                        "missing argument data type(s) for '%s' in field: %s.%s", type.CQL,
                        field.getDeclaringClass().getName(), field.getName());
                org.apache.commons.lang3.Validate.isTrue(!((type.NUM_ARGUMENTS == 0) && (atypes.size() != 0)),
                        "data type '%s' is not a collection in field: %s.%s", type.CQL,
                        field.getDeclaringClass().getName(), field.getName());
                org.apache.commons.lang3.Validate.isTrue(!(atypes.size() > type.NUM_ARGUMENTS),
                        "too many argument data type(s) for '%s' in field: %s.%s", type.CQL,
                        field.getDeclaringClass().getName(), field.getName());
                if (type.NUM_ARGUMENTS != 0) {
                    org.apache.commons.lang3.Validate.isTrue(((DataType) atypes.get(0)).NUM_ARGUMENTS == 0,
                            "collection of collection is not supported in field: %s.%s",
                            field.getDeclaringClass().getName(), field.getName());
                    org.apache.commons.lang3.Validate.isTrue(
                            !((type.NUM_ARGUMENTS > 1) && (((DataType) atypes.get(1)).NUM_ARGUMENTS != 0)),
                            "collection of collection is not supported in field: %s.%s",
                            field.getDeclaringClass().getName(), field.getName());
                    if ((((DataType) atypes.get(0)) == DataType.INFERRED) || ((type.NUM_ARGUMENTS > 1)
                            && (((DataType) atypes.get(1)) == DataType.INFERRED))) {
                        // we have an inferred part for the collection so calculate as
                        // if it was all inferred and extract only the part we need
                        final List<CQLDataType> types = new ArrayList<>(3);

                        DataTypeImpl.inferDataTypeFrom(field, field.getType(), types);
                        for (int i = 0; i < atypes.size(); i++) {
                            if (atypes.get(i) == DataType.INFERRED) {
                                atypes.set(i, types.get(i + 1)); // since index 1 corresponds to the collection type
                            }
                        }
                    }
                }
                // TODO: should probably check that the CQL specified matches a supported class for it
                return new Definition(type, atypes);
            }
        }
    }
    // if we get here then the type was either not inferred or there was no
    // Column.Data annotation or there was a Persisted annotation
    final Column.Data cdata = field.getAnnotation(Column.Data.class);

    if (cdata != null) { // also annotated with @Column.Data
        // only type supported here is either INFERRED which falls through as if
        // no data type specified or BLOB
        final DataType type = cdata.type();

        if (type == DataType.BLOB) {
            return new Definition(DataType.BLOB);
        }
        org.apache.commons.lang3.Validate.isTrue(type == DataType.INFERRED,
                "unsupported data type '%s' in @Persisted annotated field: %s.%s", type.CQL,
                field.getDeclaringClass().getName(), field.getName());
    }
    final List<CQLDataType> types = new ArrayList<>(3);

    DataTypeImpl.inferDataTypeFrom(field, field.getType(), types);
    return new Definition(types);
}

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

/**
 * Link objects together//from   ww w .  j av a2 s .  c  om
 */
public void link(Map<String, Object> model) throws Exception {

    // Iterate class by class
    for (String link : annotatedLinkFields.keySet()) {
        List<Field> linkFields = annotatedLinkFields.get(link);

        // Iterate through Link fields list
        for (Field field : linkFields) {

            // Change protection for private field
            field.setAccessible(true);

            // Retrieve linked object
            String toClassName = field.getType().getName();
            Object to = model.get(toClassName);

            ObjectHelper.notNull(to, "No @link annotation has been defined for the oject to link");
            field.set(model.get(field.getDeclaringClass().getName()), to);
        }
    }
}

From source file:org.scub.foundation.framework.core.oval.validator.AbstractValidator.java

/**
 * Get the attribut name with it's class name and package for the given field.
 * @param field the field/*from w w  w.j  a v  a2 s  . c o  m*/
 * @return the atribut name (package.class.attributName)
 */
protected String getAttributName(Field field) {
    return field.getDeclaringClass().getSimpleName() + POINT + field.getName();
}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public Pair<ConsistencyLevel, ConsistencyLevel> findConsistencyLevels(Field field,
        Pair<ConsistencyLevel, ConsistencyLevel> defaultConsistencyLevels) {
    log.debug("Find consistency configuration for field {} of class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());

    Consistency clevel = field.getAnnotation(Consistency.class);

    ConsistencyLevel defaultGlobalRead = defaultConsistencyLevels.left;
    ConsistencyLevel defaultGlobalWrite = defaultConsistencyLevels.right;

    if (clevel != null) {
        defaultGlobalRead = clevel.read();
        defaultGlobalWrite = clevel.write();
    }/*  w w  w  . java 2s .  c  o  m*/

    log.trace("Found consistency levels : {} / {}", defaultGlobalRead, defaultGlobalWrite);
    return Pair.create(defaultGlobalRead, defaultGlobalWrite);
}

From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java

private <T> List<Field> findFields(Class<T> type) {
    Field[] fields = type.getDeclaredFields();
    if (this.sortProperties) {
        // Order the fields
        Arrays.sort(fields, new Comparator<Field>() {
            public int compare(Field m1, Field m2) {
                return m1.getName().compareTo(m2.getName());
            }//from  w ww.  j  av a  2 s. c o  m
        });
    }
    List<Field> props = new ArrayList<Field>();
    // get fields
    for (Field field : fields) {
        Class<?> declaringClass = field.getDeclaringClass();
        if (declaringClass.equals(Object.class) || Collection.class.isAssignableFrom(declaringClass)) {
            continue;
        }

        String name = field.getName();
        if (field.getName().equalsIgnoreCase(name)) {
            Attributes attrs = field.getAnnotation(Attributes.class);
            // Only process annotated fields if processAnnotatedOnly set
            if (attrs != null || !this.processAnnotatedOnly) {
                props.add(field);
            }
        }
    }
    return props;
}

From source file:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Field f) {
    return canUse(f, f.getDeclaringClass());
}

From source file:br.gov.frameworkdemoiselle.internal.implementation.ConfigurationEnumValueExtractor.java

@Override
public Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception {
    String value = configuration.getString(prefix + key);

    if (value != null && !value.trim().equals("")) {
        Object enums[] = field.getType().getEnumConstants();

        for (int i = 0; i < enums.length; i++) {
            if (((Enum<?>) enums[i]).name().equals(value)) {
                return enums[i];
            }/*from   w  w  w.  ja v  a2 s .  com*/
        }
    } else {
        return null;
    }

    throw new ConversionException(getBundle().getString("configuration-not-conversion", value,
            field.getDeclaringClass().getCanonicalName()));
}