Java Reflection Method Annotation getMethodsWithAnnotation(Class type, Class annotation, boolean checkSuper)

Here you can find the source of getMethodsWithAnnotation(Class type, Class annotation, boolean checkSuper)

Description

Gets a list of all methods within a class that are marked with an annotation.

License

Open Source License

Parameter

Parameter Description
type the class to search
annotation the annotation to match
checkSuper whether or not to check all of the class' supertypes

Return

the relevant list of methods

Declaration

public static List<Method> getMethodsWithAnnotation(Class<?> type, Class<? extends Annotation> annotation,
        boolean checkSuper) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*www .jav  a2  s  . com*/
     * Gets a list of all methods within a class that are marked with an annotation.
     *
     * @param type       the class to search
     * @param annotation the annotation to match
     * @param checkSuper whether or not to check all of the class' supertypes
     * @return the relevant list of methods
     */
    public static List<Method> getMethodsWithAnnotation(Class<?> type, Class<? extends Annotation> annotation,
            boolean checkSuper) {
        List<Method> methods = new ArrayList<>();

        Class<?> clazz = type;
        while (clazz != Object.class) {
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(annotation)) {
                    methods.add(method);
                }
            }

            if (!checkSuper) {
                break;
            }

            clazz = clazz.getSuperclass();
        }

        return methods;
    }

    /**
     * Gets a list of all methods within a class that are marked with an annotation.
     *
     * @param type       the class to search
     * @param annotation the annotation to match
     * @return the relevant list of methods
     */
    public static List<Method> getMethodsWithAnnotation(Class<?> type, Class<? extends Annotation> annotation) {
        return getMethodsWithAnnotation(type, annotation, false);
    }
}

Related

  1. getMethodsAnnotatedWith(final Class type, final Class annotation)
  2. getMethodsInAnnotation(Annotation anno)
  3. getMethodsWithAnnotation(Class annotation, Class clazz)
  4. getMethodsWithAnnotation(Class type, Class obj)
  5. getMethodsWithAnnotation(Class clazz, Class annotationType)
  6. getMethodsWithAnnotation(final Class clazz, final Class... annotationClasses)
  7. getMethodValue(Class annotationClasss, Class targetClass, String... annotationFields)