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.opensymphony.able.introspect.PropertyInfo.java

protected <T extends Annotation> T findAnnotation(Class<T> clazz) {
    String name = descriptor.getName();
    try {//w  w  w  .j  a  v a  2  s. c  o  m
        Field field = entityClass.getDeclaredField(name);
        T a = field.getAnnotation(clazz);
        if (a != null) {
            return a;
        }
    } catch (NoSuchFieldException e) {
        // this should generally never happen...
    }

    Method readMethod = descriptor.getReadMethod();
    if (readMethod != null) {
        return AnnotationUtils.getAnnotation(readMethod, clazz);
    }

    return null;
}

From source file:io.druid.guice.JsonConfigurator.java

public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException {
    verifyClazzIsConfigurable(clazz);/*from ww w. j  a  v  a  2s .  c  o  m*/

    // Make it end with a period so we only include properties with sub-object thingies.
    final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + ".";

    Map<String, Object> jsonMap = Maps.newHashMap();
    for (String prop : props.stringPropertyNames()) {
        if (prop.startsWith(propertyBase)) {
            final String propValue = props.getProperty(prop);
            Object value;
            try {
                // If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote.
                String modifiedPropValue = propValue;
                if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) {
                    modifiedPropValue = String.format("\"%s\"", modifiedPropValue);
                }
                value = jsonMapper.readValue(modifiedPropValue, Object.class);
            } catch (IOException e) {
                log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
                value = propValue;
            }

            jsonMap.put(prop.substring(propertyBase.length()), value);
        }
    }

    final T config;
    try {
        config = jsonMapper.convertValue(jsonMap, clazz);
    } catch (IllegalArgumentException e) {
        throw new ProvisionException(
                String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e);
    }

    final Set<ConstraintViolation<T>> violations = validator.validate(config);
    if (!violations.isEmpty()) {
        List<String> messages = Lists.newArrayList();

        for (ConstraintViolation<T> violation : violations) {
            String path = "";
            try {
                Class<?> beanClazz = violation.getRootBeanClass();
                final Iterator<Path.Node> iter = violation.getPropertyPath().iterator();
                while (iter.hasNext()) {
                    Path.Node next = iter.next();
                    if (next.getKind() == ElementKind.PROPERTY) {
                        final String fieldName = next.getName();
                        final Field theField = beanClazz.getDeclaredField(fieldName);

                        if (theField.getAnnotation(JacksonInject.class) != null) {
                            path = String.format(" -- Injected field[%s] not bound!?", fieldName);
                            break;
                        }

                        JsonProperty annotation = theField.getAnnotation(JsonProperty.class);
                        final boolean noAnnotationValue = annotation == null
                                || Strings.isNullOrEmpty(annotation.value());
                        final String pathPart = noAnnotationValue ? fieldName : annotation.value();
                        if (path.isEmpty()) {
                            path += pathPart;
                        } else {
                            path += "." + pathPart;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                throw Throwables.propagate(e);
            }

            messages.add(String.format("%s - %s", path, violation.getMessage()));
        }

        throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() {
            @Nullable
            @Override
            public Message apply(@Nullable String input) {
                return new Message(String.format("%s%s", propertyBase, input));
            }
        }));
    }

    log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config);

    return config;
}

From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java

@SuppressWarnings("unchecked")
protected void configureBeanDistributedResources(Object annotatedBean)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    MaraAnnotationUtil util = MaraAnnotationUtil.INSTANCE;
    Distribute distribute;/*  www.j  a v a  2  s .  c  o  m*/
    // Search for annotated resources to distribute
    List<Field> fields = util.findAnnotatedFields(annotatedBean.getClass(), Distribute.class);
    for (Field field : fields) {
        distribute = field.getAnnotation(Distribute.class);
        String key = StringUtils.isBlank(distribute.name()) ? field.getName() : distribute.name();

        field.setAccessible(true);
        Object value = field.get(annotatedBean);
        if (value != null) {
            registerResource(key, value);
        }
    }

    // Search for annotated methods
    List<Method> methods = util.findAnnotatedMethods(annotatedBean.getClass(), Distribute.class);
    for (Method method : methods) {
        distribute = AnnotationUtils.findAnnotation(method, Distribute.class);
        // Invoke the method to retrieve the cache file path. Needs to return either a String or a Path
        String defaultName = StringUtils.uncapitalize(StringUtils.removeStart(method.getName(), "get"));
        String key = StringUtils.isBlank(distribute.name()) ? defaultName : distribute.name();
        Object value = method.invoke(annotatedBean);
        if (value != null) {
            registerResource(key, value);
        }
    }
}

From source file:com.wavemaker.tools.apidocs.tools.parser.impl.ReflectionModelParser.java

protected String findFieldName(Field field) {
    String name = field.getName();
    if (field.isAnnotationPresent(JsonProperty.class)) {
        final String value = field.getAnnotation(JsonProperty.class).value();
        if (StringUtils.isNotBlank(value)) {
            name = value;//from   w  w  w  .  j a va2 s  .c o m
        }
    }
    return name;
}

From source file:com.vilt.minium.jasmine.MiniumJasmineTestRunner.java

@Override
protected Object createTestClassInstance() {
    try {/*from  ww w.j a va 2  s. c  o m*/
        final Object testInstance = super.createTestClassInstance();
        contextManager.prepareTestInstance(testInstance);

        ReflectionUtils.doWithFields(testClass, new FieldCallback() {

            @Override
            public void doWith(Field f) throws IllegalArgumentException, IllegalAccessException {
                f.setAccessible(true);
                JsVariable jsVariable = f.getAnnotation(JsVariable.class);
                if (jsVariable == null)
                    return;

                String varName = jsVariable.value();
                checkNotNull(varName, "@JsVariable.value() should not be null");
                Object fieldVal = f.get(testInstance);
                Object val = getVal(jsVariable, f.getType(), fieldVal);
                put(rhinoContext, varName, val);

                if (fieldVal == null && val != null) {
                    f.set(testInstance, val);
                }
            }
        });

        return testInstance;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.stylesheet.StylesheetValidationTest.java

private Resource getXsltStylesheet(Class<? extends S2SFormGenerator> generatorClass) {
    try {/*from  ww w .jav  a2  s.c o  m*/
        final Field stylesheet = generatorClass.getDeclaredField("stylesheet");
        stylesheet.setAccessible(true);
        final Value value = stylesheet.getAnnotation(Value.class);
        final ResourceLoader resourceLoader = new DefaultResourceLoader(this.getClass().getClassLoader());
        return resourceLoader.getResource(value.value());
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(generatorClass.getName() + " cannot find stylesheet", e);
    }
}

From source file:info.archinnov.achilles.entity.parsing.EmbeddedIdParser.java

private Integer extractReversedClusteredKey(Class<?> embeddedIdClass) {
    @SuppressWarnings("unchecked")
    Set<Field> candidateFields = getFields(embeddedIdClass, ReflectionUtils.<Field>withAnnotation(Order.class));
    List<Integer> reversedFields = new LinkedList<Integer>();
    for (Field candidateField : candidateFields) {
        Order orderAnnotation = candidateField.getAnnotation(Order.class);
        if (orderAnnotation.reversed()) {
            reversedFields.add(orderAnnotation.value());
        }//  w  w w  .  jav a  2  s  .  c o m
    }
    Validator.validateBeanMappingTrue(reversedFields.size() <= 1,
            "There should be at most 1 field annotated with @Order(reversed=true) for the @EmbeddedId class '%s'",
            embeddedIdClass.getCanonicalName());
    return reversedFields.size() > 0 ? reversedFields.get(0) : null;

}

From source file:be.fedict.trust.service.snmp.SNMPInterceptor.java

private void injectSnmpFields(Object target) {

    for (Field field : target.getClass().getDeclaredFields()) {
        SNMP fieldSnmp = field.getAnnotation(SNMP.class);
        if (null == fieldSnmp) {
            continue;
        }/*from   w w w .j a v  a  2 s  .c  o  m*/

        // retrieve the current value of the associated SNMP counter
        Long value = getValue(fieldSnmp.oid(), fieldSnmp.service());

        // put this value in the map to compare afterwards
        this.values.put(field.getName(), value);

        // inject the value into the field
        field.setAccessible(true);
        try {
            field.set(target, value);
        } catch (Exception e) {
            LOG.error("Failed to set field=" + field.getName() + " value to " + value, e);
        }
    }
}

From source file:be.fedict.trust.service.snmp.SNMPInterceptor.java

private void updateSnmpDerivedFields(Object target) {

    for (Field field : target.getClass().getDeclaredFields()) {
        SNMP fieldSnmp = field.getAnnotation(SNMP.class);
        if (null == fieldSnmp || !fieldSnmp.derived()) {
            continue;
        }/*from   w ww  .  jav a 2 s  .c om*/

        // retrieve the possibly changed field value
        field.setAccessible(true);
        Long value;
        try {
            value = (Long) field.get(target);
        } catch (Exception e) {
            LOG.error("Failed to get field=" + field.getName() + " value", e);
            return;
        }

        // set the SNMP value
        setValue(fieldSnmp.oid(), fieldSnmp.service(), value);
    }

}