Java Code Examples for java.lang.reflect.Method#getDeclaredAnnotations()

The following examples show how to use java.lang.reflect.Method#getDeclaredAnnotations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceFieldNameTransformer.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Extract name to be used by Katharsis from getter's name. It uses
 * {@link ResourceFieldNameTransformer#getMethodName(Method)}, {@link JsonProperty} annotation and
 * {@link PropertyNamingStrategy}.
 *
 * @param method method to extract name
 * @return method name
 */
public String getName(Method method) {
    String name = getMethodName(method);

    if (method.isAnnotationPresent(JsonProperty.class) &&
        !"".equals(method.getAnnotation(JsonProperty.class).value())) {
        name = method.getAnnotation(JsonProperty.class).value();
    } else if (serializationConfig != null && serializationConfig.getPropertyNamingStrategy() != null) {
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        AnnotationMap annotationMap = buildAnnotationMap(declaredAnnotations);

        int paramsLength = method.getParameterAnnotations().length;
        AnnotationMap[] paramAnnotations = new AnnotationMap[paramsLength];
        for (int i = 0; i < paramsLength; i++) {
            AnnotationMap parameterAnnotationMap = buildAnnotationMap(method.getParameterAnnotations()[i]);
            paramAnnotations[i] = parameterAnnotationMap;
        }

        AnnotatedClass annotatedClass = AnnotatedClassBuilder.build(method.getDeclaringClass(), serializationConfig);
        AnnotatedMethod annotatedField = AnnotatedMethodBuilder.build(annotatedClass, method, annotationMap, paramAnnotations);
        name = serializationConfig.getPropertyNamingStrategy().nameForGetterMethod(serializationConfig, annotatedField, name);
    }
    return name;
}
 
Example 2
Source File: TypeModuleFactory.java    From weex with Apache License 2.0 6 votes vote down vote up
private void generateMethodMap() {
  WXLogUtils.d(TAG, "extractMethodNames");
  ArrayList<String> methods = new ArrayList<>();
  HashMap<String, Invoker> methodMap = new HashMap<>();
  try {
    for (Method method : mClazz.getMethods()) {
      // iterates all the annotations available in the method
      for (Annotation anno : method.getDeclaredAnnotations()) {
        if (anno != null && anno instanceof WXModuleAnno) {
          methods.add(method.getName());
          methodMap.put(method.getName(), new MethodInvoker(method));
          break;
        }
      }
    }
  } catch (Throwable e) {
    WXLogUtils.e("[WXModuleManager] extractMethodNames:" + e.getStackTrace());
  }
  mMethods = methods;
  mMethodMap = methodMap;
}
 
Example 3
Source File: TypeRegistry.java    From glitr with MIT License 6 votes vote down vote up
private GraphQLOutputType getGraphQLOutputTypeFromAnnotationsOnGetter(Class declaringClass, Method method) {
    GraphQLOutputType graphQLOutputType = null;
    Annotation[] methodAnnotations = method.getDeclaredAnnotations();
    for (Annotation annotation: methodAnnotations) {
        // custom OutputType
        if (annotationToGraphQLOutputTypeMap.containsKey(annotation.annotationType())) {
            Func5<TypeRegistry, Field, Method, Class, Annotation, GraphQLOutputType> customGraphQLOutputTypeFunc = annotationToGraphQLOutputTypeMap.get(annotation.annotationType());
            GraphQLOutputType outputType = customGraphQLOutputTypeFunc.call(this, null, method, declaringClass, annotation);
            if (outputType != null) {
                graphQLOutputType = outputType;
                break;
            }
        }
    }
    return graphQLOutputType;
}
 
Example 4
Source File: ActionInvoker.java    From restcommander with Apache License 2.0 6 votes vote down vote up
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
    if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
        return invoke(method, null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
    } else if (Modifier.isStatic(method.getModifiers())) {
        Object[] args = getActionMethodArgs(method, null);
        args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
        return invoke(method, null, args);
    } else {
        Object instance = null;
        try {
            instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
        } catch (Exception e) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            String annotation = Utils.getSimpleNames(annotations);
            if (!StringUtils.isEmpty(annotation)) {
                throw new UnexpectedException("Method public static void " + method.getName() + "() annotated with " + annotation + " in class " + method.getDeclaringClass().getName() + " is not static.");
            }
            // TODO: Find a better error report
            throw new ActionNotFoundException(Http.Request.current().action, e);
        }
        return invoke(method, instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
    }
}
 
Example 5
Source File: TypeRegistry.java    From glitr with MIT License 6 votes vote down vote up
private DataFetcher getDataFetcherFromAnnotationsOnGetter(Class declaringClass, Method method) {
    Annotation[] methodAnnotations = method.getDeclaredAnnotations();
    for (Annotation annotation: methodAnnotations) {
        // custom fetchers
        Class annotationType = annotation.annotationType();
        if (annotationToDataFetcherFactoryMap.containsKey(annotationType)) {
            AnnotationBasedDataFetcherFactory annotationBasedDataFetcherFactory = annotationToDataFetcherFactoryMap.get(annotationType);
            DataFetcher dataFetcher = annotationBasedDataFetcherFactory.create(null, method, declaringClass, annotation);
            if (dataFetcher != null) {
                return dataFetcher;
            }
        } else if (annotationToDataFetcherMap.containsKey(annotationType)) {
            return annotationToDataFetcherMap.get(annotationType);
        }
    }
    return null;
}
 
Example 6
Source File: ImmutableBeans.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Looks for an annotation by class name.
 * Useful if you don't want to depend on the class
 * (e.g. "javax.annotation.Nonnull") at compile time. */
private static boolean hasAnnotation(Method method, String className) {
  for (Annotation annotation : method.getDeclaredAnnotations()) {
    if (annotation.annotationType().getName().equals(className)) {
      return true;
    }
  }
  return false;
}
 
Example 7
Source File: RxBodyWriterTest.java    From rx-jersey with MIT License 5 votes vote down vote up
private OutputStream testWriteTo(String methodName, MediaType mediaType, Object entity, OutputStream outputStream) throws NoSuchMethodException, IOException {

        final MessageBodyFactory messageBodyFactory = injectionManager.getInstance(MessageBodyFactory.class);

        final Method textMethod = TestResource.class.getMethod(methodName);
        final Type genericReturnType = textMethod.getGenericReturnType();
        final Annotation[] annotations = textMethod.getDeclaredAnnotations();

        final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>(
                Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Collections.singletonList(mediaType))
        );

        return messageBodyFactory.writeTo(entity, entity.getClass(), genericReturnType, annotations, mediaType, headers,
                new MapPropertiesDelegate(), outputStream, Collections.emptyList());
    }
 
Example 8
Source File: MethodTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.lang.reflect.Method#getDeclaredAnnotations()
 */
public void test_getDeclaredAnnotations() throws Exception {
    Method method = TestMethod.class.getDeclaredMethod("annotatedMethod");
    Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
    assertEquals(2, declaredAnnotations.length);

    Set<Class<?>> annotationSet = new HashSet<Class<?>>();
    annotationSet.add(declaredAnnotations[0].annotationType());
    annotationSet.add(declaredAnnotations[1].annotationType());
    assertTrue("Missing TestAnno annotation", annotationSet
            .contains(TestAnno.class));
    assertTrue("Missing Deprecated annotation", annotationSet
            .contains(Deprecated.class));
}
 
Example 9
Source File: ReflectionUtils.java    From AstralEdit with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the annotation of the given method
 *
 * @param method          method
 * @param annotationClazz annotation
 * @param <T>             returnType
 * @return returnValue
 */
public static <T extends Annotation> T invokeAnnotationByMethod(Method method, Class<T> annotationClazz) {
    if (method == null)
        throw new IllegalArgumentException("Method cannot be null!");
    if (annotationClazz == null)
        throw new IllegalArgumentException("AnnotationClass cannot be null!");
    for (final Annotation annotation : method.getDeclaredAnnotations()) {
        if (annotation.annotationType() == annotationClazz)
            return (T) annotation;
    }
    return null;
}
 
Example 10
Source File: ParticipantAttributeExtractor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public static Map<ParticipantAttribute, Object> getAttributes(Object targetObject)
{
    Map<ParticipantAttribute, Object> attributes = new HashMap<ParticipantAttribute, Object>();


    PropertyDescriptor[] descriptors;
    try
    {
        descriptors = BeanUtils.getPropertyDescriptors(targetObject);
    }
    catch (IntrospectionException e)
    {
        throw new RuntimeException(e);
    }
    for (PropertyDescriptor propertyDescriptor : descriptors)
    {
        final Method readMethod = getPropertyReadMethod(targetObject, propertyDescriptor);

        for (Annotation annotation : readMethod.getDeclaredAnnotations())
        {
            if (annotation instanceof OutputAttribute)
            {
                OutputAttribute outputAttribute = (OutputAttribute) annotation;

                Object value = getPropertyValue(targetObject, propertyDescriptor.getName());
                attributes.put(outputAttribute.attribute(), value);
            }
        }
    }

    return attributes;
}
 
Example 11
Source File: ComponentHolder.java    From weex with Apache License 2.0 5 votes vote down vote up
private synchronized void generate(){
  WXLogUtils.d(TAG,"Generate Component:"+mClz.getSimpleName());
  HashMap<String, Invoker> methods = new HashMap<>();

  Annotation[] annotations;
  Annotation anno;
  for (Method method : mClz.getMethods()) {
    annotations = method.getDeclaredAnnotations();
    for (int i = 0,annotationsCount = annotations.length;
         i < annotationsCount; ++i) {
      anno = annotations[i];
      if (anno != null && anno instanceof WXComponentProp) {
        String name = ((WXComponentProp) anno).name();
        methods.put(name, new MethodInvoker(method));
        break;
      }
    }
  }

  mMethods = methods;
  try {
    mConstructor = mClz.getConstructor(WXSDKInstance.class, WXDomObject.class, WXVContainer.class, boolean.class);
  } catch (NoSuchMethodException e) {
    try {
      //compatible deprecated constructor
      mConstructor = mClz.getConstructor(WXSDKInstance.class, WXDomObject.class, WXVContainer.class,String.class, boolean.class);
    } catch (NoSuchMethodException e1) {
      e1.printStackTrace();
      throw new WXRuntimeException("Can't find constructor of component.");
    }
    e.printStackTrace();
  }
}
 
Example 12
Source File: HttpMethodPredicate.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public boolean test(Method candidate) {
    for (Annotation annotation : candidate.getDeclaredAnnotations()) {
        if (annotation.annotationType().getAnnotation(HttpMethod.class) != null) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: HintScanner.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Finds the JSON-HOME hints on the given method.
 *
 * @param method the method to scan
 * @return the hints
 */
public Hints findHint(Method method) {
    Hints hints = new Hints();
    for (Annotation annotation : method.getDeclaredAnnotations()) {
        findAllow(hints, annotation);
        findFormats(hints, annotation);
    }
    return hints;
}
 
Example 14
Source File: TaskBase.java    From pravega with Apache License 2.0 5 votes vote down vote up
private Task getTaskAnnotation(final String method) {
    for (Method m : this.getClass().getMethods()) {
        if (m.getName().equals(method)) {
            for (Annotation annotation : m.getDeclaredAnnotations()) {
                if (annotation instanceof Task) {
                    return (Task) annotation;
                }
            }
            break;
        }
    }
    throw new TaskAnnotationNotFoundException(method);
}
 
Example 15
Source File: TestInterfaceAlign.java    From hbase with Apache License 2.0 5 votes vote down vote up
private boolean isDeprecated(Method method) {
  Annotation[] annotations = method.getDeclaredAnnotations();
  for (Annotation annotation : annotations) {
    if (annotation instanceof Deprecated) {
      return true;
    }
  }
  return false;
}
 
Example 16
Source File: JAXRSClassVisitor.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
private static boolean hasJAXRSAnnotations(final Method method) {
    for (final Object annotation : method.getDeclaredAnnotations()) {
        // TODO test both
        if (Stream.of(RELEVANT_METHOD_ANNOTATIONS).map(a -> JavaUtils.getAnnotation(method, a))
                .filter(Objects::nonNull).anyMatch(a -> a.getClass().isAssignableFrom(annotation.getClass())))
            return true;

        if (isAnnotationPresent(annotation.getClass(), HttpMethod.class))
            return true;
    }
    return false;
}
 
Example 17
Source File: HttpMethodFactory.java    From nubes with Apache License 2.0 5 votes vote down vote up
public static Map<HttpMethod, String> fromAnnotatedMethod(Method method) {
  Map<HttpMethod, String> methods = new EnumMap<>(HttpMethod.class);
  for (Annotation annot : method.getDeclaredAnnotations()) {
    Class<? extends Annotation> annotClass = annot.annotationType();
    putIfHttpMethod(methods, annot, annotClass);
  }
  return methods;
}
 
Example 18
Source File: AnnotationProcessor.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
/**
 * Get Resources for each API
 *
 * @param resourceRootContext
 * @param annotatedMethods
 * @return
 * @throws Throwable
 */
private List<Permission> getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable {

    List<Permission> permissions = new ArrayList<>();
    Permission permission;
    String subCtx;
    for (Method method : annotatedMethods) {
        Annotation[] annotations = method.getDeclaredAnnotations();

        if (isHttpMethodAvailable(annotations)) {
            Annotation methodContextAnno = method.getAnnotation(pathClazz);
            if (methodContextAnno != null) {
                subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING);
            } else {
                subCtx = WILD_CARD;
            }
            permission = new Permission();
            // this check is added to avoid url resolving conflict which happens due
            // to adding of '*' notation for dynamic path variables.
            if (WILD_CARD.equals(subCtx)) {
                subCtx = makeContextURLReady(resourceRootContext);
            } else {
                subCtx = makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx);
            }
            permission.setUrl(replaceDynamicPathVariables(subCtx));
            String httpMethod;
            for (int i = 0; i < annotations.length; i++) {
                httpMethod = getHTTPMethodAnnotation(annotations[i]);
                if (httpMethod != null) {
                    permission.setMethod(httpMethod);
                }
                if (annotations[i].annotationType().getName().
                        equals(io.swagger.annotations.ApiOperation.class.getName())) {
                    this.setPermission(annotations[i], permission);
                }
            }
            if (permission.getName() == null || permission.getPath() == null) {
                log.warn("Permission not assigned to the resource url - " + permission.getMethod() + ":"
                                 + permission.getUrl());
            } else {
                permissions.add(permission);
            }
        }
    }
    return permissions;
}
 
Example 19
Source File: CSRF.java    From actframework with Apache License 2.0 4 votes vote down vote up
public static Spec spec(Method action) {
    Type type = Method.class;
    Annotation[] annotations = action.getDeclaredAnnotations();
    return spec(BeanSpec.of(type, annotations, Act.injector()));
}
 
Example 20
Source File: AnnotationProcessor.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
/**
 * Get Resources for each API
 *
 * @param resourceRootContext
 * @param annotatedMethods
 * @return
 * @throws Throwable
 */
private List<APIResource> getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable {
    List<APIResource> resourceList = new ArrayList<>();
    String subCtx = null;
    for (Method method : annotatedMethods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        APIResource resource = new APIResource();
        if (isHttpMethodAvailable(annotations)) {
            Annotation methodContextAnno = method.getAnnotation(pathClazz);
            if (methodContextAnno != null) {
                subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING);
            } else {
                subCtx = WILD_CARD;
            }
            resource.setUriTemplate(makeContextURLReady(subCtx));
            resource.setUri(APIPublisherUtil.getServerBaseUrl() + makeContextURLReady(resourceRootContext) +
                    makeContextURLReady(subCtx));
            resource.setAuthType(AUTH_TYPE);
            for (int i = 0; i < annotations.length; i++) {
                processHTTPMethodAnnotation(resource, annotations[i]);
                if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) {
                    Method[] consumesClassMethods = consumesClass.getMethods();
                    Annotation consumesAnno = method.getAnnotation(consumesClass);
                    resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR));
                }
                if (annotations[i].annotationType().getName().equals(Produces.class.getName())) {
                    Method[] producesClassMethods = producesClass.getMethods();
                    Annotation producesAnno = method.getAnnotation(producesClass);
                    resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR));
                }
                if (annotations[i].annotationType().getName().equals(ApiOperation.class.getName())) {
                    ApiScope scope = this.getScope(annotations[i]);
                    if (scope != null) {
                        resource.setScope(scope);
                    } else {
                        log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
                                makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
                        scope = new ApiScope();
                        scope.setName(DEFAULT_SCOPE_NAME);
                        scope.setDescription(DEFAULT_SCOPE_NAME);
                        scope.setKey(DEFAULT_SCOPE_KEY);
                        scope.setRoles(DEFAULT_SCOPE_PERMISSION);
                        resource.setScope(scope);
                    }
                }
            }
            resourceList.add(resource);
        }
    }
    return resourceList;
}