Example usage for java.lang.reflect Method getAnnotation

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

Introduction

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

Prototype

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

Source Link

Usage

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

@Test
public void timedNullCollectionParameterMethod() {
    List<String> list = null;
    Timer timedMethod = forTimedMethod(metricRegistry, MetricParamClass.class, "timedCollectionParameterMethod",
            list);/*from   ww  w  .  j a  va2  s .c o  m*/
    assertNull(timedMethod);

    metricParamClass.timedCollectionParameterMethod(list);
    timedMethod = forTimedMethod(metricRegistry, MetricParamClass.class, "timedCollectionParameterMethod",
            list);
    assertNotNull(timedMethod);
    assertEquals(1, timedMethod.getCount());

    Method method = findMethod(MetricParamClass.class, "timedCollectionParameterMethod");
    String metricName = forTimedMethod(MetricParamClass.class, method, method.getAnnotation(Timed.class), list);
    assertEquals("timed-collection-param.size.0", metricName);
}

From source file:org.assertj.db.common.AbstractTest.java

@After
public void determineIfReloadIsNeeded() throws NoSuchMethodException, SecurityException {
    Annotation classAnnotation = getClass().getAnnotation(NeedReload.class);
    if (classAnnotation != null) {
        return;/*from  ww  w .j  ava2 s  .  com*/
    }
    String methodName = testNameRule.getMethodName();
    Method method = getClass().getDeclaredMethod(methodName);
    Annotation methodAnnotation = method.getAnnotation(NeedReload.class);
    if (methodAnnotation != null) {
        return;
    }
    dbSetupTracker.skipNextLaunch();
}

From source file:net.firejack.platform.core.validation.NotMatchProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
    NotMatch notMatchAnnotation = readMethod.getAnnotation(NotMatch.class);
    if (notMatchAnnotation != null && StringUtils.isNotBlank(notMatchAnnotation.expression())) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class) {
            Pattern pattern = getCachedPatterns().get(notMatchAnnotation.expression());
            if (pattern == null) {
                try {
                    pattern = Pattern.compile(notMatchAnnotation.expression());
                    getCachedPatterns().put(notMatchAnnotation.expression(), pattern);
                } catch (PatternSyntaxException e) {
                    logger.error(e.getMessage(), e);
                    throw new ImproperValidationArgumentException(
                            "Pattern expression should have correct syntax.");
                }// w w w  .  j a  v a2 s.  c  om
            }
            if (value != null) {
                String sValue = (String) value;
                if (StringUtils.isNotBlank(sValue) && pattern.matcher(sValue).matches()) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(),
                            notMatchAnnotation.parameterName()));
                }
            }
        }
    }

    if (notMatchAnnotation != null && !notMatchAnnotation.javaWords()) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class && StringUtils.isNotBlank((String) value)) {
            String s = (String) value;
            for (String word : words) {
                if (word.equals(s)) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(), word));
                }
            }
        }
    }

    return messages;
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.parser.XmlParserSubject.java

private void invokeAnnotatedElementMethod(String elementName, String elementValue, ParserObserver observer,
        Method method) {
    ElementMatcher annos = method.getAnnotation(ElementMatcher.class);

    if (annos == null) {
        return;//from   w w w  . j  a v a  2 s. co m
    }
    if (elementName.equals(annos.elementName())) {
        invokeMethod(elementValue, observer, method);
    }
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

/**
 * NOTE: this is a brittle example of walking up the stack to find
 * an annotated method to determine how to treat the API doc captured in this
 * Intercepter. The use of annotations provides a lightweight mechanism of doing just that.
 *
 * @return the rank if found (or the ApiDocExample.DEFAULT_RANK if not)
 *//*from  ww  w  . j  a  va 2s  .c o  m*/
private int getRankOfApiDoc() {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    // default to DEFAULT_RANK which will capture the doc, but put it at the bottom if no annotation is found.
    int rank = ApiDocExample.DEFAULT_RANK;
    // loop up the stack to find the annotation
    for (int i = 0; i < stack.length; i++) {
        StackTraceElement ste = stack[i];
        // shortcut up the stack: once we get to the MocMvc call, we're in business: start interrogating the methods
        if (ste.getClassName().equals(MockMvc.class.getName())) {
            for (int j = i; j < stack.length; j++) {
                StackTraceElement theOne = stack[j];
                try {
                    Class<?> clazz = Class.forName(theOne.getClassName());
                    // following JUnit convention, the root test will have no args
                    Method theMethod = clazz.getMethod(theOne.getMethodName(), (Class[]) null);
                    // find the ApiDocExample if it exists
                    ApiDocExample example = theMethod.getAnnotation(ApiDocExample.class);
                    if (example != null) {
                        rank = example.rank();
                        // once we find an example annotation, break out of loops.
                        break;
                    }
                } catch (ClassNotFoundException | NoSuchMethodException e) {
                    // getMethod failed to find a no arg method, continue down the stack.
                    continue;
                }
            }
            break;
        }
    }
    return rank;
}

From source file:org.bytesoft.bytetcc.supports.spring.CompensableAnnotationValidator.java

private void validateTransactionalRollbackFor(Method method, Class<?> clazz, String beanName)
        throws IllegalStateException {
    Transactional transactional = method.getAnnotation(Transactional.class);
    if (transactional == null) {
        Class<?> declaringClass = method.getDeclaringClass();
        transactional = declaringClass.getAnnotation(Transactional.class);
    }

    if (transactional == null) {
        throw new IllegalStateException(
                String.format("Method(%s) must be specificed a Transactional annotation!", method));
    }//from www  . j a  v a2 s  .c  om

    String[] rollbackForClassNameArray = transactional.rollbackForClassName();
    if (rollbackForClassNameArray != null && rollbackForClassNameArray.length > 0) {
        throw new IllegalStateException(String.format(
                "The transactional annotation on the confirm/cancel class does not support the property rollbackForClassName yet(beanId= %s)!",
                beanName));
    }

    Class<?>[] rollErrorArray = transactional.rollbackFor();

    Class<?>[] errorTypeArray = method.getExceptionTypes();
    for (int j = 0; errorTypeArray != null && j < errorTypeArray.length; j++) {
        Class<?> errorType = errorTypeArray[j];
        if (RuntimeException.class.isAssignableFrom(errorType)) {
            continue;
        }

        boolean matched = false;
        for (int k = 0; rollErrorArray != null && k < rollErrorArray.length; k++) {
            Class<?> rollbackError = rollErrorArray[k];
            if (rollbackError.isAssignableFrom(errorType)) {
                matched = true;
                break;
            }
        }

        if (matched == false) {
            throw new IllegalStateException(String.format(
                    "The value of Transactional.rollbackFor annotated on method(%s) must includes %s!", method,
                    errorType.getName()));
        }
    }
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.parser.XmlParserSubject.java

private void invokeAnnotatedMethod(String elementName, String attributeValue, String attributeName,
        ParserObserver observer, Method method) {
    AttributeMatcher annos = method.getAnnotation(AttributeMatcher.class);

    if (annos == null) {
        return;//from www .ja va 2  s  .  c om
    }
    if (elementName.equals(annos.elementName()) && attributeName.equals(annos.attributeName())) {
        invokeMethod(attributeValue, observer, method);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

/**
 * Tests that anything annotated with {@link JsxGetter} does not start with "set" and vice versa.
 *//* w w w .j  a v a2  s  . c om*/
@Test
public void methodPrefix() {
    for (final Class<?> klass : JavaScriptConfiguration.CLASSES_) {
        for (final Method method : klass.getMethods()) {
            final String methodName = method.getName();
            if (method.getAnnotation(JsxGetter.class) != null && methodName.startsWith("set")) {
                fail("Method " + methodName + " in " + klass.getSimpleName()
                        + " should not start with \"set\"");
            }
            if (method.getAnnotation(JsxSetter.class) != null && methodName.startsWith("get")) {
                fail("Method " + methodName + " in " + klass.getSimpleName()
                        + " should not start with \"get\"");
            }
        }
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.config.AnnotationStyleIT.java

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void annotationStyleNoneProducesNoAnnotations()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("annotationStyle", "none"));

    Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

    Method getter = generatedType.getMethod("getA");

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue()));
    assertThat(generatedType.getAnnotation(JsonSerialize.class), is(nullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue()));

}

From source file:org.fishwife.jrugged.spring.PerformanceMonitorBeanFactory.java

/**
 * Create the initial {@link PerformanceMonitorBean} instances.
 *//*from w  w w  . j  av a 2  s .co  m*/
public void createInitialPerformanceMonitors() {
    if (packageScanBase != null) {
        AnnotatedMethodScanner methodScanner = new AnnotatedMethodScanner();
        for (Method m : methodScanner.findAnnotatedMethods(packageScanBase,
                org.fishwife.jrugged.aspects.PerformanceMonitor.class)) {
            org.fishwife.jrugged.aspects.PerformanceMonitor performanceMonitorAnnotation = m
                    .getAnnotation(org.fishwife.jrugged.aspects.PerformanceMonitor.class);
            initialPerformanceMonitorList.add(performanceMonitorAnnotation.value());
        }
    }
    for (String name : initialPerformanceMonitorList) {
        createPerformanceMonitor(name);
    }
}