Java Method from Class getAllMethodsWithAnnotation( String packageName, Class annotation)

Here you can find the source of getAllMethodsWithAnnotation( String packageName, Class annotation)

Description

get All Methods With Annotation

License

Open Source License

Declaration

public static Set<Method> getAllMethodsWithAnnotation(
            String packageName, Class<? extends Annotation> annotation) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * QMetry Automation Framework provides a powerful and versatile platform to
 * author// w w  w . j  a  v  a2 s  .c  o m
 * Automated Test Cases in Behavior Driven, Keyword Driven or Code Driven
 * approach
 * Copyright 2016 Infostretch Corporation
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT
 * OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE
 * You should have received a copy of the GNU General Public License along with
 * this program in the name of LICENSE.txt in the root folder of the
 * distribution. If not, see https://opensource.org/licenses/gpl-3.0.html
 * See the NOTICE.TXT file in root folder of this source files distribution
 * for additional information regarding copyright ownership and licenses
 * of other open source software / files used by QMetry Automation Framework.
 * For any inquiry or need additional information, please contact
 * support-qaf@infostretch.com
 *******************************************************************************/

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import java.util.Enumeration;
import java.util.HashSet;

import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    private static final String CLASS_SUFIX = ".class";
    private static final String PROTOCOL_JAR = "jar";

    public static Set<Method> getAllMethodsWithAnnotation(
            String packageName, Class<? extends Annotation> annotation) {
        Set<Method> methods = new HashSet<Method>();
        try {
            for (Class<?> cls : getClasses(packageName)) {
                for (Method method : cls.getMethods()) {
                    if (hasAnnotation(method, annotation)) {
                        methods.add(method);
                    }
                }
            }
        } catch (SecurityException e) {
            System.err
                    .println("ClassUtil.getAllMethods: " + e.getMessage());
        } catch (IOException e) {
            System.err
                    .println("ClassUtil.getAllMethods: " + e.getMessage());
        }

        return methods;
    }

    public static List<Class<?>> getClasses(String pkg) throws IOException {
        ClassLoader classLoader = Thread.currentThread()
                .getContextClassLoader();
        String path = pkg.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<Class<?>> classes = new ArrayList<Class<?>>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (resource.getProtocol().equalsIgnoreCase(PROTOCOL_JAR)) {
                try {
                    classes.addAll(getClassesFromJar(resource, pkg));
                } catch (IOException e) {
                    System.err.println("Unable to get classes from jar: "
                            + resource);
                }
            } else {
                try {
                    classes.addAll(getClasses(new File(resource.toURI()),
                            pkg));
                } catch (URISyntaxException e) {
                    // ignore it
                }
            }
        }
        return classes;
    }

    /**
     * Recursive method used to find all classes in a given directory and
     * subdirs.
     * 
     * @param directory
     *            The base directory
     * @param packageName
     *            The package name for classes found inside the base directory
     * @return The classes
     */
    private static List<Class<?>> getClasses(File directory,
            String packageName) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(getClasses(file,
                        packageName + "." + file.getName()));
            } else if (file.getName().endsWith(CLASS_SUFIX)) {
                String clsName = packageName
                        + '.'
                        + file.getName().substring(0,
                                file.getName().lastIndexOf("."));
                try {
                    classes.add(Class.forName(clsName));
                } catch (ClassNotFoundException e) {
                    // ignore it
                }
            }
        }
        return classes;
    }

    public static boolean hasAnnotation(Method method,
            Class<? extends Annotation> annotation) {
        if (method.isAnnotationPresent(annotation))
            return true;
        Class<?>[] intfaces = method.getDeclaringClass().getInterfaces();
        for (Class<?> intface : intfaces) {
            try {
                if (intface.getMethod(method.getName(),
                        method.getParameterTypes()).isAnnotationPresent(
                        annotation))
                    return true;
            } catch (NoSuchMethodException e) {
                // Ignore!...
            } catch (SecurityException e) {
                // Ignore!...
            }

        }
        return false;
    }

    private static List<Class<?>> getClassesFromJar(URL jar, String pkg)
            throws IOException {
        List<Class<?>> classes = new ArrayList<Class<?>>();

        String jarFileName = URLDecoder.decode(jar.getFile(), "UTF-8");
        jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
        JarFile jf = new JarFile(jarFileName);
        Enumeration<JarEntry> jarEntries = jf.entries();

        while (jarEntries.hasMoreElements()) {
            String entryName = jarEntries.nextElement().getName()
                    .replace("/", ".");
            if (entryName.startsWith(pkg)
                    && entryName.endsWith(CLASS_SUFIX)) {
                entryName = entryName.substring(0,
                        entryName.lastIndexOf('.'));
                try {
                    classes.add(Class.forName(entryName));
                } catch (Throwable e) {
                    System.err.println("Unable to get class " + entryName
                            + " from jar " + jarFileName);
                }
            }
        }
        jf.close();

        return classes;
    }

    /**
     * Get all methods of the class including parent.
     * 
     * @param clazz
     * @param name
     *            case-insensitive method name to get
     * @return
     * @throws NoSuchMethodException
     */
    public static Method getMethod(Class<?> clazz, String name)
            throws NoSuchMethodException {
        Method[] methods = clazz.getMethods();
        for (Method m : methods) {
            if (m.getName().equalsIgnoreCase(name)) {
                return m;
            }
        }
        if (null != clazz.getSuperclass()) {
            getMethod(clazz.getSuperclass(), name);
        }
        throw new NoSuchMethodException();
    }
}

Related

  1. existsMethod(final String clazz, final String name, final Class[] parameterTypes)
  2. findMethod(Class javaClass, String methodName, Class[] methodParameterTypes)
  3. findMethod(Class c, String name, Class params[])
  4. findMethod(Method m, Class c)
  5. findMethods(Class c)
  6. getDeclaredMethod(final Class clazz, final String methodName, final Class[] methodParameterTypes)
  7. getMethod(Class type, Method m)
  8. getMethod(final Class javaClass, final String methodName, final Class[] methodParameterTypes, final boolean shouldSetAccessible)
  9. getMethods(final Class clazz)