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:edu.usu.sdl.openstorefront.validation.ValidValueRule.java

@Override
protected String getValidationRule(Field field) {
    StringBuilder sb = new StringBuilder();
    ValidValueType validValueType = field.getAnnotation(ValidValueType.class);
    sb.append("Set of valid values: ").append(Arrays.toString(validValueType.value()));
    return sb.toString();
}

From source file:com.conversantmedia.mapreduce.mrunit.UnitTestDistributedResourceManager.java

protected void distributeValue(Map<String, Object> values, Object bean)
        throws IllegalArgumentException, IllegalAccessException {
    @SuppressWarnings("unchecked")
    List<Field> fields = MaraAnnotationUtil.INSTANCE.findAnnotatedFields(bean.getClass(), Resource.class);
    for (Field field : fields) {
        Resource resAnnotation = field.getAnnotation(Resource.class);
        String property = StringUtils.isEmpty(resAnnotation.name()) ? field.getName() : resAnnotation.name();
        Object value = values.get(property);
        if (value != null) {
            DistributedResourceManager.setFieldValue(field, bean, value);
        }/*w w  w . ja v  a2 s  .  c o m*/
    }
}

From source file:management.limbr.data.model.util.EntityUtil.java

public String getDisplayName(BaseEntity entity) {
    if (entity == null) {
        return "null";
    }//from ww w .  j a  v a 2 s .  c  om

    for (Field field : entity.getClass().getDeclaredFields()) {
        if (field.getAnnotation(DisplayName.class) != null) {
            Object value = callGetter(entity, field.getName());
            if (value == null) {
                return "null";
            } else {
                return value.toString();
            }
        }
    }

    return entity.getClass().getSimpleName();
}

From source file:com.sunsprinter.diffunit.core.injection.Injector.java

protected void inject(final Class<?> currentClass, final Class<?> testClass, final Object test)
        throws DiffUnitInjectionException {
    if (currentClass != Object.class) {
        for (final Field field : currentClass.getDeclaredFields()) {
            final DiffUnitInject annotation = field.getAnnotation(DiffUnitInject.class);
            if (annotation != null) {
                final Object key = StringUtils.isEmpty(annotation.objectId()) ? field.getType()
                        : annotation.objectId();

                final boolean fieldAccessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(test, getInjectionMap().get(key));
                } catch (final Exception e) {
                    throw new DiffUnitInjectionException(String.format(
                            "DiffUnit unable to inject field '%s' of class '%s' on test of class '%s'.  "
                                    + "Component key is '%s'.  Target field type is '%s'.",
                            field.getName(), currentClass.getName(), testClass.getName(), key,
                            field.getType().getName()), e);
                } finally {
                    field.setAccessible(fieldAccessible);
                }/*from  www  .ja  v a  2 s  .  com*/
            }
        }

        inject(currentClass.getSuperclass(), testClass, test);
    }
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Inspects a {@link Model} class and returns all of the available and acceptable query parameter
 *   definitions, as a map of parameter names and {@link QueryParameterDescriptor} objects.
 * /*ww w . j  av  a2  s.com*/
 * @param model
 * @return
 */
public static Map<String, QueryParameterDescriptor> getAvailableQueryParameters(Class<? extends Model<?>> model,
        boolean recursive) {
    Map<String, QueryParameterDescriptor> paramMap = new HashMap<>();
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        Class<?> type = field.getType();
        if (Collection.class.isAssignableFrom(field.getType())) {
            ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            type = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
        if (field.isAnnotationPresent(Ignored.class)) {
            continue;
        } else {
            paramMap.put(fieldName,
                    new QueryParameterDescriptor(fieldName, fieldName, type, Evaluation.EQUALS));
        }
        if (field.isAnnotationPresent(ForeignKey.class)) {
            if (!recursive)
                continue;
            ForeignKey foreignKey = field.getAnnotation(ForeignKey.class);
            String relField = !"".equals(foreignKey.rel()) ? foreignKey.rel() : fieldName;
            Map<String, QueryParameterDescriptor> foreignModelMap = getAvailableQueryParameters(
                    foreignKey.model(), false);
            for (QueryParameterDescriptor descriptor : foreignModelMap.values()) {
                String newParamName = relField + "." + descriptor.getParamName();
                descriptor.setParamName(newParamName);
                paramMap.put(newParamName, descriptor);
            }
        }
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                paramMap.put(alias.value(),
                        new QueryParameterDescriptor(alias.value(),
                                alias.fieldName().equals("") ? fieldName : alias.fieldName(), type,
                                alias.evaluation()));
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            paramMap.put(alias.value(), new QueryParameterDescriptor(alias.value(),
                    alias.fieldName().equals("") ? fieldName : alias.fieldName(), type, alias.evaluation()));
        }
    }
    return paramMap;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java

@Override
public Set<String> getIndexRangeKeyPropertyNames() {
    final Set<String> propertyNames = new HashSet<String>();
    ReflectionUtils.doWithMethods(getJavaType(), new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBIndexRangeKey.class) != null) {
                if ((method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null
                        && method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim()
                                .length() > 0)
                        || (method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null
                                && method.getAnnotation(DynamoDBIndexRangeKey.class)
                                        .localSecondaryIndexNames().length > 0)) {
                    propertyNames.add(getPropertyNameForAccessorMethod(method));
                }/*from w  ww.java2  s  .co  m*/
            }
        }
    });
    ReflectionUtils.doWithFields(getJavaType(), new FieldCallback() {
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBIndexRangeKey.class) != null) {
                if ((field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null
                        && field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim()
                                .length() > 0)
                        || (field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null
                                && field.getAnnotation(DynamoDBIndexRangeKey.class)
                                        .localSecondaryIndexNames().length > 0)) {
                    propertyNames.add(getPropertyNameForField(field));
                }
            }
        }
    });
    return propertyNames;
}

From source file:com.cognifide.slice.mapper.impl.processor.SliceReferenceFieldProcessor.java

@Override
public Object mapResourceToField(final Resource resource, final ValueMap valueMap, final Field field,
        final String propertyName) {
    final SliceReference sliceReferenceAnnotation = field.getAnnotation(SliceReference.class);
    final String initialPath = sliceReferenceAnnotation.value();
    final String fullPath = getFullPath(initialPath);
    final Class<?> fieldType = field.getType();
    return modelProvider.get().get(fieldType, fullPath);
}

From source file:com.cassius.spring.assembly.test.common.process.MockOnBeanProcessor.java

/**
 * Do process before.//w  w  w  .j  a v a 2  s . c  o m
 *
 * @param context the context
 * @param instance the instance
 * @param field the field
 * @throws Exception the exception
 */
@Override
protected void doProcessBefore(ApplicationContext context, Object instance, Field field) throws Exception {
    FieldWriter.newInstance(instance, field,
            Mockito.spy(context.getBean(field.getAnnotation(MockOnBean.class).value()))).write();
}

From source file:com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor.java

protected final void populateIdColumn(EntityMetadata metadata, Class<?> clazz, Field f) {
    if (f.isAnnotationPresent(Column.class)) {
        Column c = f.getAnnotation(Column.class);
        if (!c.name().isEmpty()) {
            metadata.setIdColumn(metadata.new Column(c.name(), f));
        }//from w ww.j  av a 2 s  . c  om
    }
}

From source file:io.github.benas.jpopulator.impl.BeanValidationRandomizer.java

/**
 * Generate a random value according to the validation constraint present on a field.
 *
 * @param field the field to populate//from  w w  w  .j a  v  a  2  s.c  om
 * @return a random value according to the validation constraint
 */
public static Object getRandomValue(final Field field) {

    Class<?> fieldType = field.getType();

    Object result = null;

    if (field.isAnnotationPresent(AssertFalse.class)) {
        result = false;
    }
    if (field.isAnnotationPresent(AssertTrue.class)) {
        result = true;
    }
    if (field.isAnnotationPresent(Null.class)) {
        result = null;
    }
    if (field.isAnnotationPresent(Future.class)) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, ConstantsUtil.DEFAULT_DATE_RANGE);
        result = new DateRangeRandomizer(new Date(), calendar.getTime()).getRandomValue();
    }
    if (field.isAnnotationPresent(Past.class)) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -ConstantsUtil.DEFAULT_DATE_RANGE);
        result = new DateRangeRandomizer(calendar.getTime(), new Date()).getRandomValue();
    }
    if (field.isAnnotationPresent(Max.class)) {
        Max maxAnnotation = field.getAnnotation(Max.class);
        long maxValue = maxAnnotation.value();
        result = MaxValueRandomizer.getRandomValue(fieldType, maxValue);
    }
    if (field.isAnnotationPresent(DecimalMax.class)) {
        DecimalMax decimalMaxAnnotation = field.getAnnotation(DecimalMax.class);
        BigDecimal decimalMaxValue = new BigDecimal(decimalMaxAnnotation.value());
        result = MaxValueRandomizer.getRandomValue(fieldType, decimalMaxValue.longValue());
    }
    if (field.isAnnotationPresent(Min.class)) {
        Min minAnnotation = field.getAnnotation(Min.class);
        long minValue = minAnnotation.value();
        result = MinValueRandomizer.getRandomValue(fieldType, minValue);
    }
    if (field.isAnnotationPresent(DecimalMin.class)) {
        DecimalMin decimalMinAnnotation = field.getAnnotation(DecimalMin.class);
        BigDecimal decimalMinValue = new BigDecimal(decimalMinAnnotation.value());
        result = MinValueRandomizer.getRandomValue(fieldType, decimalMinValue.longValue());
    }
    if (field.isAnnotationPresent(Size.class)) {
        Size sizeAnnotation = field.getAnnotation(Size.class);
        int minSize = sizeAnnotation.min();
        int maxSize = sizeAnnotation.max();
        result = RandomStringUtils.randomAlphabetic(new RandomDataGenerator().nextInt(minSize, maxSize));
    }
    return result;

}