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.googlecode.jsonschema2pojo.integration.config.CustomAnnotatorIT.java

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

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/primitiveProperties.json",
            "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName()));

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

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

    assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue()));
    assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue()));

    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue()));
    assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue()));
}

From source file:org.vaadin.spring.i18n.Translator.java

private void analyzeMethods(Class<?> clazz) {
    for (Method m : clazz.getDeclaredMethods()) {
        if (m.getParameterTypes().length == 0 && m.getReturnType() != Void.TYPE) {
            if (m.isAnnotationPresent(TranslatedProperty.class)) {
                translatedMethods.put(m.getAnnotation(TranslatedProperty.class), m);
            } else if (m.isAnnotationPresent(TranslatedProperties.class)) {
                for (TranslatedProperty annotation : m.getAnnotation(TranslatedProperties.class).value()) {
                    translatedMethods.put(annotation, m);
                }//from  w  w  w  . j  a  v a2s.co  m
            }
        }
    }
}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

private Method findRestMethod(RESTMethod method, Class<?> clazz, String url) {
    for (Method m : clazz.getMethods()) {
        REST rest = m.getAnnotation(REST.class);
        if (rest != null && rest.url().equals(url) && rest.method() == method) {
            return m;
        }//ww w .j  a v a  2  s  .c  om
    }
    return null;
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

private boolean isPrimaryKey(Method method) {
    return isPublic(method.getModifiers())
            && (method.getAnnotation(Id.class) != null || method.getAnnotation(EmbeddedId.class) != null);
}

From source file:org.flite.cach3.aop.UpdateSingleCacheAdvice.java

private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable {
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return;/*from w  w w  . j  a v a 2  s .  c om*/
    }

    final MemcachedClientIF cache = getMemcachedClient();
    final Method methodToCache = getMethodToCache(jp);
    List<UpdateSingleCache> lAnnotations;

    if (methodToCache.getAnnotation(UpdateSingleCache.class) != null) {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateSingleCache.class));
    } else {
        lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateSingleCaches.class).value());
    }

    for (int i = 0; i < lAnnotations.size(); i++) {
        // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
        // but do not let it surface up past the AOP injection itself.
        try {
            final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName(),
                    getJitterDefault());
            final String baseKey = CacheBase.getBaseKey(info.getAsString(AType.KEY_TEMPLATE),
                    info.getAsInteger(AType.KEY_INDEX, null), retVal, jp.getArgs(), methodToCache.toString(),
                    factory, methodStore);
            final String cacheKey = buildCacheKey(baseKey, info.getAsString(AType.NAMESPACE),
                    info.getAsString(AType.KEY_PREFIX));
            Object dataObject = getIndexObject(info.getAsInteger(AType.DATA_INDEX, null), retVal, jp.getArgs(),
                    methodToCache.toString());
            dataObject = UpdateSingleCacheAdvice.getMergedData(dataObject,
                    info.getAsString(AType.DATA_TEMPLATE, null), retVal, jp.getArgs(), factory);
            final Class dataTemplateType = (Class) info.getAsType(AType.DATA_TEMPLATE_TYPE, String.class);
            final Object submission = (dataObject == null) ? new PertinentNegativeNull()
                    : applyDataTemplateType(dataObject, dataTemplateType);

            boolean cacheable = true;
            if (submission instanceof CacheConditionally) {
                cacheable = ((CacheConditionally) submission).isCacheable();
            }

            if (cacheable) {
                cache.set(cacheKey, calculateJitteredExpiration(info.getAsInteger(AType.EXPIRATION),
                        info.getAsInteger(AType.JITTER)), submission);
            }

            // Notify the observers that a cache interaction happened.
            final List<UpdateSingleCacheListener> listeners = getPertinentListeners(
                    UpdateSingleCacheListener.class, info.getAsString(AType.NAMESPACE));
            if (listeners != null && !listeners.isEmpty()) {
                for (final UpdateSingleCacheListener listener : listeners) {
                    try {
                        listener.triggeredUpdateSingleCache(info.getAsString(AType.NAMESPACE),
                                info.getAsString(AType.KEY_PREFIX, null), baseKey, dataObject, retVal,
                                jp.getArgs());
                    } catch (Exception ex) {
                        LOG.warn("Problem when triggering a listener.", ex);
                    }
                }
            }
        } catch (Exception ex) {
            if (LOG.isDebugEnabled()) {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
            } else {
                LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
            }
        }
    }
}

From source file:net.erdfelt.android.sdkfido.configer.Configer.java

private void findRawArgsMethod(Class<?> clazz) {
    for (Method method : clazz.getDeclaredMethods()) {
        ConfigArguments arg = method.getAnnotation(ConfigArguments.class);
        if (arg == null) {
            continue; // skip, not tagged
        }//  www.  j a va2s  .c  o  m

        int mods = method.getModifiers();
        if (!Modifier.isPublic(mods)) {
            continue; // skip, not public
        }

        if (Modifier.isStatic(mods)) {
            continue; // skip, dont support static
        }

        Class<?>[] params = method.getParameterTypes();
        if (params == null) {
            continue; // skip, needs params
        }

        if (params.length != 1) {
            continue; // skip, needs 1 param
        }

        if (!(params[0].equals(String.class))) {
            continue; // skip, param must be String
        }

        if (this.rawArgAdder != null) {
            StringBuilder err = new StringBuilder();
            err.append("Not allowed to have multiple @ConfigArguments defined: ");
            err.append("\n  Duplicate found at ").append(clazz.getName()).append("#").append(method.getName());
            err.append("\n  Original found at ").append(rawArgAdder.getDeclaringClass().getName()).append("#")
                    .append(rawArgAdder.getName());
            throw new IllegalStateException(err.toString());
        }

        this.rawArgAdder = method;
    }
}

From source file:com.clican.pluto.cms.core.service.impl.DataModelServiceImpl.java

public Map<String, Object> convertToMap(IDataModel obj) {
    Map<String, Object> map = new HashMap<String, Object>();
    Method[] methods = obj.getClass().getMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(DynamicProperty.class)) {
            try {
                Object value = method.invoke(obj, new Object[] {});
                DynamicProperty dp = method.getAnnotation(DynamicProperty.class);
                String name = dp.name();
                String firstCharLowerName = name.substring(0, 1).toLowerCase() + name.substring(1);
                map.put(firstCharLowerName, value);
            } catch (Exception e) {
                log.error("", e);
            }//from  ww  w  . j  a  va2  s. c  o m

        }
    }
    return map;
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

@SuppressWarnings("WeakerAccess")
public JsonApiResourceDeserializer(String apiType, Class<T> klass) {
    this.klass = klass;
    this.apiType = apiType;

    for (Field field : FieldUtils.getAllFieldsList(klass)) {
        ResourceId resourceId = field.getAnnotation(ResourceId.class);
        if (resourceId != null) {
            validateResourceId(field.getType());
            idSetter = new FieldSetter(field);
        }/*from w w  w .  ja  v a 2  s  .c  o  m*/
        Relationship relationship = field.getAnnotation(Relationship.class);
        if (relationship != null) {
            String name = validateRelationship(field.getType(), relationship);
            relationshipSetters.put(name, new FieldSetter(field));
        }
        ResourceLink resourceLink = field.getAnnotation(ResourceLink.class);
        if (resourceLink != null) {
            String name = validateResourceLink(field.getType(), resourceLink);
            linkSetters.put(name, new FieldSetter(field));
        }
    }

    for (Method method : klass.getDeclaredMethods()) {
        ResourceId resourceId = method.getAnnotation(ResourceId.class);
        if (resourceId != null) {
            validateMethodParameters(ResourceId.class, method);
            idSetter = new MethodSetter(method);
        }
        Relationship relationship = method.getAnnotation(Relationship.class);
        if (relationship != null) {
            Class<?> parameter = validateMethodParameters(Relationship.class, method);
            String name = validateRelationship(parameter, relationship);
            relationshipSetters.put(name, new MethodSetter(method));
        }
        ResourceLink resourceLink = method.getAnnotation(ResourceLink.class);
        if (resourceLink != null) {
            Class<?> parameter = validateMethodParameters(ResourceLink.class, method);
            String name = validateResourceLink(parameter, resourceLink);
            linkSetters.put(name, new MethodSetter(method));
        }
    }
    if (idSetter == null) {
        throw new IllegalStateException("Must provide a ResourceId for " + klass);
    }
}

From source file:com.frameworkx.mvc.ControllerRouteHandler.java

/**
 * Determine what method from the controller class to call
 *
 * @param methodName/*from ww  w.  ja v  a 2s .c  o m*/
 * @param clss
 * @return
 */
private Method chooseMethod(final String methodName, final Class<? extends Controller> clss,
        final HttpServletRequest request) {
    for (Method func : clss.getMethods()) {
        if (func.getName().equals(methodName)) {
            // check HTTP method
            HttpMethod annotation = func.getAnnotation(HttpMethod.class);
            if (annotation != null) {
                if (annotation.value() != null && !annotation.value().isEmpty()) {
                    final String httpMethod = request.getMethod();
                    if (!annotation.value().contains(httpMethod)) {
                        continue;
                    }
                }
            }

            return func;
        }
    }
    return null;
}

From source file:com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.java

/**
 * Retrieves an annotation for the specified field of getter.
 *
 * @param parentClass     the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property        the property of the Map or Collection for the given parent class
 * @param annotationClass The annotation
 * @return concrete Annotation instance or <tt>null</tt> if none could be retrieved.
 *///from   ww  w.ja v a 2s  . c o  m
private <T extends Annotation> T getAnnotationFromGetter(Class parentClass, String property,
        Class<T> annotationClass) {
    try {
        Method getter = reflectionProvider.getGetMethod(parentClass, property);

        if (getter != null) {
            return getter.getAnnotation(annotationClass);
        }
    } catch (ReflectionException | IntrospectionException e) {
        // ignore
    }
    return null;
}