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.evolveum.midpoint.prism.xml.XmlTypeConverter.java

public static <T> T toXmlEnum(Class<T> expectedType, String stringValue) {
    if (stringValue == null) {
        return null;
    }/*  w  w w  .  j  a  va  2  s . c  o m*/
    for (T enumConstant : expectedType.getEnumConstants()) {
        Field field;
        try {
            field = expectedType.getField(((Enum) enumConstant).name());
        } catch (SecurityException e) {
            throw new IllegalArgumentException(
                    "Error getting field from '" + enumConstant + "' in " + expectedType, e);
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException(
                    "Error getting field from '" + enumConstant + "' in " + expectedType, e);
        }
        XmlEnumValue annotation = field.getAnnotation(XmlEnumValue.class);
        if (annotation.value().equals(stringValue)) {
            return enumConstant;
        }
    }
    throw new IllegalArgumentException("No enum value '" + stringValue + "' in " + expectedType);
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }/*www  .  ja v  a 2  s  .c  o  m*/

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:kelly.core.injector.AbstractSpringInjector.java

@Override
public final void inject(Object bean) {
    if (bean == null)
        return;// w w  w.  j  a v  a  2s .  c o  m

    Field[] fields = getFieldsIncludingSuperclass(bean);

    for (Field field : fields) {
        Inject inject = field.getAnnotation(Inject.class);
        boolean nullable = field.getAnnotation(Nullable.class) != null;
        if (inject == null) {
            continue;
        } else {

            String beanName = inject.value();
            Object com = null;
            if ("".equals(beanName)) { // 
                com = getBeanFromApplicationContext(field.getType());
            } else {
                com = getBeanFromApplicationContext(beanName);
            }

            if (com == null) {
                if (nullable) {
                    continue;
                } else {
                    throw new InjectException("Inject failed for field " + field.toString());
                }
            }
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, bean, com);
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.runners.FrameworkMethodWithParameters.java

/**
 * {@inheritDoc}/*from   w  w  w  . j av a2 s  .c o  m*/
 */
@Override
public Object invokeExplosively(final Object target, final Object... params) throws Throwable {
    if (!parameters_.isEmpty()) {
        final List<FrameworkField> annotatedFieldsByParameter = testClass_.getAnnotatedFields(Parameter.class);
        if (annotatedFieldsByParameter.size() != parameters_.size()) {
            throw new Exception("Wrong number of parameters and @Parameter fields."
                    + " @Parameter fields counted: " + annotatedFieldsByParameter.size()
                    + ", available parameters: " + parameters_.size() + ".");
        }
        for (final FrameworkField each : annotatedFieldsByParameter) {
            final Field field = each.getField();
            final Parameter annotation = field.getAnnotation(Parameter.class);
            final int index = annotation.value();
            try {
                field.set(target, parameters_.get(index));
            } catch (final IllegalArgumentException iare) {
                throw new Exception(testClass_.getName() + ": Trying to set " + field.getName()
                        + " with the value " + parameters_.get(index) + " that is not the right type ("
                        + parameters_.get(index).getClass().getSimpleName() + " instead of "
                        + field.getType().getSimpleName() + ").", iare);
            }
        }
    }
    return super.invokeExplosively(target, params);
}

From source file:com.graphaware.importer.domain.Neo4jPropertyContainer.java

private synchronized void initializeForClass(Class<?> clazz) {
    if (CACHE.containsKey(clazz.getCanonicalName())) {
        return;/*www.  java2 s  .  co m*/
    }

    Set<Pair<Field, String>> fieldsAndNames = new HashSet<>();

    for (Field field : ReflectionUtils.getAllFields(clazz)) {
        Neo4jProperty annotation = field.getAnnotation(Neo4jProperty.class);
        if (annotation == null) {
            continue;
        }

        String fieldName = StringUtils.isEmpty(annotation.name()) ? field.getName() : annotation.name();
        fieldsAndNames.add(new Pair<>(field, fieldName));
        field.setAccessible(true);
    }

    CACHE.put(clazz.getCanonicalName(), fieldsAndNames);
}

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

@SuppressWarnings("unchecked")
protected void addDistributedProperties(Class<?> clazz, List<String> properties) {
    Distribute distribute;//from   w  w  w.  ja v  a 2 s  . co m
    MaraAnnotationUtil util = MaraAnnotationUtil.INSTANCE;
    List<Field> fields = util.findAnnotatedFields(clazz, Distribute.class);
    for (Field field : fields) {
        distribute = field.getAnnotation(Distribute.class);
        String prop = StringUtils.isBlank(distribute.name()) ? field.getName() : distribute.name();
        properties.add(prop);
    }

    List<Method> methods = util.findAnnotatedMethods(clazz, Distribute.class);
    for (Method method : methods) {
        distribute = AnnotationUtils.findAnnotation(method, Distribute.class);
        String defaultName = StringUtils.uncapitalize(StringUtils.removeStart(method.getName(), "get"));
        String prop = StringUtils.isBlank(distribute.name()) ? defaultName : distribute.name();
        properties.add(prop);
    }
}

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

@Override
protected void withField(Object bean, String beanName, Class<?> targetClass, Field field) {
    final Metric annotation = field.getAnnotation(Metric.class);
    final String metricName = Util.forMetricField(targetClass, field, annotation);

    final Class<?> type = field.getType();
    if (!com.codahale.metrics.Metric.class.isAssignableFrom(type)) {
        throw new IllegalArgumentException("Field " + targetClass.getCanonicalName() + "." + field.getName()
                + " must be a subtype of " + com.codahale.metrics.Metric.class.getCanonicalName());
    }/*w w w.j av  a  2 s. c o m*/

    ReflectionUtils.makeAccessible(field);

    // Get the value of the field annotated with @Metric
    com.codahale.metrics.Metric metric = (com.codahale.metrics.Metric) ReflectionUtils.getField(field, bean);

    if (metric == null) {
        // If null, create a metric of the appropriate type and inject it
        metric = getMetric(metrics, type, metricName);
        ReflectionUtils.setField(field, bean, metric);
        LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                field.getName());
    } else {
        // If non-null, register that instance of the metric
        try {
            // Attempt to register that instance of the metric
            metrics.register(metricName, metric);
            LOG.debug("Registered metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        } catch (IllegalArgumentException ex1) {
            // A metric is already registered under that name
            // (Cannot determine the cause without parsing the Exception's message)
            try {
                metric = getMetric(metrics, type, metricName);
                ReflectionUtils.setField(field, bean, metric);
                LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                        field.getName());
            } catch (IllegalArgumentException ex2) {
                // A metric of a different type is already registered under that name
                throw new IllegalArgumentException("Error injecting metric for field "
                        + targetClass.getCanonicalName() + "." + field.getName(), ex2);
            }
        }
    }
}

From source file:py.una.pol.karaku.dao.entity.interceptors.UriInterceptor.java

@Override
public void intercept(Operation op, Field field, Object bean) {

    URI uri = notNull(field.getAnnotation(URI.class), "Intercept a field without uri in UriInterceptor");

    String baseUri = Validate.notNull(uri.baseUri(), "Base uri in a @URI is null or empty");

    String finalUri = null;//from w ww .j av a 2s.c  o m
    switch (uri.type()) {
    case FIELD:
        finalUri = byUniqueField(field, bean, uri);
        break;
    case SEQUENCE:
        finalUri = bySequence(field, uri);
        break;
    default:
        throw new IllegalArgumentException();
    }

    ReflectionUtils.setField(field, bean, baseUri + finalUri);

}

From source file:br.com.bea.androidtools.api.json.JSONContextImpl.java

public JSONContextImpl(final Class<E> targetClass) {
    this.targetClass = targetClass;
    metadata = new LinkedList<MetadataObject>();
    for (final Field field : EntityUtils.metadataFields(targetClass))
        metadata.add(new MetadataObject(field, field.getAnnotation(Metadata.class).value()));
}

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

public DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl(final Class<T> domainType) {
    super(domainType);
    this.hashAndRangeKeyMethodExtractor = new DynamoDBHashAndRangeKeyMethodExtractorImpl<T>(getJavaType());
    ReflectionUtils.doWithMethods(domainType, new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBHashKey.class) != null) {
                String setterMethodName = toSetterMethodNameFromAccessorMethod(method);
                if (setterMethodName != null) {
                    hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName,
                            method.getReturnType());
                }/*from  w w  w .j a v  a2  s .  c om*/
            }
        }
    });
    ReflectionUtils.doWithFields(domainType, new FieldCallback() {
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBHashKey.class) != null) {

                hashKeyField = ReflectionUtils.findField(domainType, field.getName());

            }
        }
    });
    Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null,
            "Unable to find hash key field or setter method on " + domainType + "!");
    Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null,
            "Found both hash key field and setter method on " + domainType + "!");

}