get Annotated Declared Methods - Java java.lang.annotation

Java examples for java.lang.annotation:Method Annotation

Description

get Annotated Declared Methods

Demo Code

/*//from www.j  a  v  a2s  . co  m
 * JFox - The most lightweight Java EE Application Server!
 * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
 *
 * JFox is licenced and re-distributable under GNU LGPL.
 */
//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Field;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clz = String.class;
        Class annotation = String.class;
        System.out.println(java.util.Arrays
                .toString(getAnnotatedDeclaredMethods(clz, annotation)));
    }

    public static Method[] getAnnotatedDeclaredMethods(Class clz,
            Class<? extends Annotation> annotation) {
        List<Method> methods = new ArrayList<Method>();
        Method[] allMethods = clz.getDeclaredMethods();
        for (int i = 0; i < allMethods.length; i++) {
            if (isAnnotated(allMethods[i], annotation)) {
                methods.add(allMethods[i]);
            }
        }
        return methods.toArray(new Method[methods.size()]);
    }

    public static boolean isAnnotated(Method method,
            Class<? extends Annotation> annotation) {
        return method.isAnnotationPresent(annotation);
    }

    public static boolean isAnnotated(Field field,
            Class<? extends Annotation> annotation) {
        return field.isAnnotationPresent(annotation);
    }
}

Related Tutorials