Example usage for java.lang.reflect Field getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:com.jedi.oracle.OracleCall.java

private void fillParametersFromFields() throws IllegalAccessException {
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(getClass(), OracleParameterMapping.class);
    if (fields == null || fields.isEmpty()) {
        return;/* ww w  .ja  va2 s.co m*/
    }

    for (Field field : fields) {
        OracleParameterMapping mapping = field.getAnnotation(OracleParameterMapping.class);
        OracleParameter parameter = new OracleParameter();
        parameter.setDbType(mapping.dbType());
        parameter.setDirection(mapping.direction());
        parameter.setIndex(mapping.index());
        parameter.setName(mapping.name());
        parameter.setOracleDbType(mapping.oracleType());
        parameter.setCustomTypeName(mapping.customTypeName());
        switch (parameter.getDirection()) {
        case Input:
        case InputOutput:
            field.setAccessible(true);
            parameter.setValue(field.get(this));
            break;
        }

        this.parameters.add(parameter);
    }
}

From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseCommand.java

public void printUsage() {
    System.out.println("Usage: " + this.getName());

    for (Field f : this.getClass().getDeclaredFields()) {
        if (f.isAnnotationPresent(Option.class)) {
            Option option = f.getAnnotation(Option.class);

            System.out.println(String.format("\t%-25s %-30s: %s (required=%s)", option.name(), option.metaVar(),
                    option.usage(), option.required()));
        }//from  ww  w .j ava 2s. c o  m
    }
}

From source file:com.nabla.wapp.server.csv.CsvReader.java

private void buildColumnList(final Class recordClass) {
    if (recordClass != null) {
        for (Field field : recordClass.getDeclaredFields()) {
            final ICsvField definition = field.getAnnotation(ICsvField.class);
            if (definition != null) {
                final ICsvSetter writer = cache.get(field.getType());
                Assert.notNull(writer,/*from  ww  w  .  ja  v  a  2s .c  om*/
                        "no CSV setter defined for type '" + field.getType().getSimpleName() + "'");
                if (!field.isAccessible())
                    field.setAccessible(true); // in order to lift restriction on 'private' fields
                final ICsvColumn column = new CsvColumn(field, writer);
                expectedColumns.put(column.getName().toLowerCase(), column);
                columns.add(column);
            }
        }
        buildColumnList(recordClass.getSuperclass());
    }
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find fields with annotation./*w w w .j  a  v  a  2 s  .c om*/
 *
 * @param clazz the clazz
 * @param annotation the annotation
 * @param res the res
 */
public static void findFieldsWithAnnotation(Class<?> clazz, Class<? extends Annotation> annotation,
        List<Pair<Field, ? extends Annotation>> res) {
    for (Field f : clazz.getDeclaredFields()) {
        Annotation an = f.getAnnotation(annotation);
        if (an == null) {
            continue;
        }
        res.add(new Pair<Field, Annotation>(f, an));
    }
    if (clazz == Object.class || clazz.getSuperclass() == null) {
        return;
    }
    findFieldsWithAnnotation(clazz.getSuperclass(), annotation, res);
}

From source file:com.ryantenney.metrics.spring.GaugeAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override/*  w  w w .jav  a  2s .c  o  m*/
        public void doWith(final Field field) throws IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            final Gauge annotation = field.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, field, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    Object value = ReflectionUtils.getField(field, bean);
                    if (value instanceof com.codahale.metrics.Gauge) {
                        value = ((com.codahale.metrics.Gauge<?>) value).getValue();
                    }
                    return value;
                }
            });

            LOG.debug("Created gauge {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override
        public void doWith(final Method method) throws IllegalAccessException {
            if (method.getParameterTypes().length > 0) {
                throw new IllegalStateException(
                        "Method " + method.getName() + " is annotated with @Gauge but requires parameters.");
            }

            final Gauge annotation = method.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, method, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    return ReflectionUtils.invokeMethod(method, bean);
                }
            });

            LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
                    method.getName());
        }
    }, FILTER);

    return bean;
}

From source file:it.unibas.spicy.persistence.object.operators.AnalyzeFields.java

private void checkReferences(List<ReferenceProperty> references) {
    for (ReferenceProperty reference : references) {
        if (reference.getInverse() != null) {
            if (logger.isDebugEnabled())
                logger.debug("Inverse is not null for reference: " + reference);
            continue;
        }/*w  w  w  . java 2  s.com*/
        if (!isInverseReference(reference)) {
            if (logger.isDebugEnabled())
                logger.debug("Annotation Inverse is not present for reference: " + reference);
            continue;
        }
        IClassNode classNode = reference.getTarget();
        Field field = reference.getField();
        String inverseValue = field.getAnnotation(Inverse.class).value();
        ReferenceProperty inverse = classNode.findReferencePropertyByName(inverseValue);
        if (logger.isDebugEnabled())
            logger.debug("Setting inverse: " + inverse.toShortString() + " for reference: "
                    + reference.toShortString());
        reference.setInverse(inverse);
        inverse.setInverse(reference);
    }
}

From source file:com.basho.riak.client.convert.RiakBeanSerializerModifier.java

/**
 * Checks if the property has any of the Riak annotations on it or the 
 * Jackson JsonProperty annotation. //from  www . j  av  a  2s.  c om
 * 
 * If a Riak annotation is present without the Jackson JsonProperty
 * annotation, this will return false.
 * 
 * If a property has been annotated with both the Jackson JsonProperty
 * annotation and a Riak annotation, the Jackson annotation takes precedent 
 * and this will return true.
 * 
 * @param beanPropertyWriter
 *            a {@link BeanPropertyWriter} to check for Riak* annotations
 * @return true if the property is not Riak annotated or is Jackson
* JsonProperty annotated, false otherwise
 */
private boolean keepProperty(BeanPropertyWriter beanPropertyWriter) {
    RiakKey key = null;
    RiakUsermeta usermeta = null;
    RiakLinks links = null;
    RiakIndex index = null;
    RiakVClock vclock = null;
    JsonProperty jacksonJsonProperty = null;
    RiakTombstone tombstone = null;

    AnnotatedMember member = beanPropertyWriter.getMember();
    if (member instanceof AnnotatedField) {
        AnnotatedElement element = member.getAnnotated();
        key = element.getAnnotation(RiakKey.class);
        usermeta = element.getAnnotation(RiakUsermeta.class);
        links = element.getAnnotation(RiakLinks.class);
        index = element.getAnnotation(RiakIndex.class);
        vclock = element.getAnnotation(RiakVClock.class);
        tombstone = element.getAnnotation(RiakTombstone.class);
        jacksonJsonProperty = element.getAnnotation(JsonProperty.class);
    } else {
        @SuppressWarnings("rawtypes")
        Class clazz = member.getDeclaringClass();
        Field field;
        try {
            field = clazz.getDeclaredField(beanPropertyWriter.getName());
            key = field.getAnnotation(RiakKey.class);
            usermeta = field.getAnnotation(RiakUsermeta.class);
            links = field.getAnnotation(RiakLinks.class);
            index = field.getAnnotation(RiakIndex.class);
            vclock = field.getAnnotation(RiakVClock.class);
            tombstone = field.getAnnotation(RiakTombstone.class);
            jacksonJsonProperty = field.getAnnotation(JsonProperty.class);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            // ignore, not a field means not a Riak annotated field.
        }
    }

    if (jacksonJsonProperty != null) {
        return true;
    } else {
        return key == null && usermeta == null && links == null && vclock == null && index == null
                && tombstone == null;
    }
}

From source file:com.frand.easyandroid.db.sql.FFUpdateSqlBuilder.java

/**
 * where?where?primaryKey/* w ww . ja va2 s . c o m*/
 * 
 * @param entity
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws FFDBException
 */
public FFArrayList buildWhere(Object entity)
        throws IllegalArgumentException, IllegalAccessException, FFDBException {
    Class<?> clazz = entity.getClass();
    FFArrayList whereArrayList = new FFArrayList();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (!FFDBUtils.isTransient(field) && FFFieldUtil.isBaseDateType(field)) {
            Annotation annotation = field.getAnnotation(FFPrimaryKey.class);
            if (annotation != null) {
                String columnName = FFDBUtils.getColumnByField(field);
                whereArrayList.add(
                        (columnName != null && !columnName.equals("")) ? columnName : field.getName(),
                        field.get(entity).toString());
            }
        }
    }
    if (whereArrayList.isEmpty()) {
        throw new FFDBException("?Where??");
    }
    return whereArrayList;
}

From source file:com.webpagebytes.cms.engine.JSONToFromObjectConverter.java

public <T> T objectFromJSONString(String jsonString, Class<T> objClass) {
    try {/*ww w.  jav  a  2 s  .c o  m*/
        org.json.JSONObject json = new org.json.JSONObject(jsonString);
        T newObj = objClass.newInstance();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            Object storeAdn = field.getAnnotation(WPBAdminFieldStore.class);
            if (storeAdn == null) {
                storeAdn = field.getAnnotation(WPBAdminFieldKey.class);
                if (storeAdn == null) {
                    storeAdn = field.getAnnotation(WPBAdminFieldTextStore.class);
                    if (storeAdn == null) {
                        storeAdn = field.getAnnotation(WPBAdminField.class);
                    }
                }
            }

            if (storeAdn != null) {
                String fieldName = field.getName();
                try {
                    PropertyDescriptor pd = new PropertyDescriptor(fieldName, objClass);
                    Object fieldValue = fieldFromJSON(json, fieldName, field.getType());
                    if (fieldValue != null) {
                        pd.getWriteMethod().invoke(newObj, fieldFromJSON(json, fieldName, field.getType()));
                    }
                } catch (Exception e) {
                    // do nothing, there is no write method for our field
                }
            }
        }

        return newObj;

    } catch (Exception e) {
        // do nothing
    }
    return null;

}

From source file:com.netflix.governator.lifecycle.ConfigurationProcessor.java

void assignConfiguration(Object obj, Field field, Map<String, String> contextOverrides) throws Exception {
    Configuration configuration = field.getAnnotation(Configuration.class);
    String configurationName = configuration.value();
    ConfigurationKey key = new ConfigurationKey(configurationName,
            KeyParser.parse(configurationName, contextOverrides));

    Object value = null;/*from w  w w  .  j  a v a2s .  c  om*/

    boolean has = configurationProvider.has(key);
    if (has) {
        try {
            if (Supplier.class.isAssignableFrom(field.getType())) {
                ParameterizedType type = (ParameterizedType) field.getGenericType();
                Class<?> actualType = (Class<?>) type.getActualTypeArguments()[0];
                Supplier<?> current = (Supplier<?>) field.get(obj);
                value = getConfigurationSupplier(field, key, actualType, current);
                if (value == null) {
                    log.error("Field type not supported: " + actualType + " (" + field.getName() + ")");
                    field = null;
                }
            } else {
                Supplier<?> supplier = getConfigurationSupplier(field, key, field.getType(),
                        Suppliers.ofInstance(field.get(obj)));
                if (supplier == null) {
                    log.error("Field type not supported: " + field.getType() + " (" + field.getName() + ")");
                    field = null;
                } else {
                    value = supplier.get();
                }
            }
        } catch (IllegalArgumentException e) {
            ignoreTypeMismtachIfConfigured(configuration, configurationName, e);
            field = null;
        } catch (ConversionException e) {
            ignoreTypeMismtachIfConfigured(configuration, configurationName, e);
            field = null;
        }
    }

    if (field != null) {
        String defaultValue;
        if (Supplier.class.isAssignableFrom(field.getType())) {
            defaultValue = String.valueOf(((Supplier<?>) field.get(obj)).get());
        } else {
            defaultValue = String.valueOf(field.get(obj));
        }

        String documentationValue;
        if (has) {
            field.set(obj, value);

            documentationValue = String.valueOf(value);
            if (Supplier.class.isAssignableFrom(field.getType())) {
                documentationValue = String.valueOf(((Supplier<?>) value).get());
            } else {
                documentationValue = String.valueOf(documentationValue);
            }
        } else {
            documentationValue = "";
        }
        configurationDocumentation.registerConfiguration(field, configurationName, has, defaultValue,
                documentationValue, configuration.documentation());
    }
}