Gets all Class files from a JarFile that extends a specific Class - Java Reflection

Java examples for Reflection:Jar

Description

Gets all Class files from a JarFile that extends a specific Class

Demo Code

/*/*from w  w w. j  a  v  a2  s . c  o  m*/
 * This file is part of VIUtils.
 *
 * Copyright ? 2012-2015 Visual Illusions Entertainment
 *
 * VIUtils is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * This library 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/lgpl.html.
 */
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class Main{
    /**
     * Gets all {@link Class} files from a {@link JarFile} that extends a specific {@link Class}
     *
     * @param jarFile
     *         the {@link JarFile} to get classes from
     * @param sCls
     *         the super {@link Class} to check extension of
     *
     * @return {@link Class} array
     *
     * @throws java.lang.ClassNotFoundException
     *         if the jar doesn't appear on the class-path and subsequently unable to load/find classes
     * @throws java.lang.NullPointerException
     *         if {@code jarFile} or {@code sCls} is null
     */
    @SuppressWarnings({ "unchecked" })
    public static <T> Class<? extends T>[] getAllClassesExtending(
            JarFile jarFile, Class<T> sCls) throws ClassNotFoundException {


        ArrayList<Class<? extends T>> classes = new ArrayList<Class<? extends T>>();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entName = entry.getName().replace("/", ".");
            if (entName.endsWith(".class")) {
                Class<?> cls = Class.forName(entName.substring(0,
                        entName.length() - 6));
                if (sCls.isAssignableFrom(cls)) {
                    classes.add(cls.asSubclass(sCls));
                }
            }
        }
        return classes.toArray(new Class[classes.size()]);
    }
}

Related Tutorials