Can you find all classes in a package using reflection?

前端 未结 27 2214
不知归路
不知归路 2020-11-21 05:24

Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

相关标签:
27条回答
  • 2020-11-21 06:08

    It is very possible, but without additional libraries like Reflections it is hard...
    It is hard because you haven't full instrument for get class name.
    And, I take the code of my ClassFinder class:

    package play.util;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    
    /**
     * Created by LINKOR on 26.05.2017 in 15:12.
     * Date: 2017.05.26
     */
    public class FileClassFinder {
    private JarFile file;
    private boolean trouble;
    public FileClassFinder(String filePath) {
        try {
            file = new JarFile(filePath);
        } catch (IOException e) {
            trouble = true;
        }
    }
    
    public List<String> findClasses(String pkg) {
        ArrayList<String> classes = new ArrayList<>();
        Enumeration<JarEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            JarEntry cls = entries.nextElement();
            if (!cls.isDirectory()) {
                String fileName = cls.getName();
                String className = fileName.replaceAll("/",         ".").replaceAll(File.pathSeparator, ".").substring(0, fileName.lastIndexOf('.'));
                if (className.startsWith(pkg)) classes.add(className.substring(pkg.length() + 1));
            }
        }
        return classes;
    }
    }
    
    0 讨论(0)
  • 2020-11-21 06:09

    Hello. I always have had some issues with the solutions above (and on other sites).
    I, as a developer, am programming a addon for a API. The API prevents the use of any external libraries or 3rd party tools. The setup also consists of a mixture of code in jar or zip files and class files located directly in some directories. So my code had to be able to work arround every setup. After a lot of research I have come up with a method that will work in at least 95% of all possible setups.

    The following code is basically the overkill method that will always work.

    The code:

    This code scans a given package for all classes that are included in it. It will only work for all classes in the current ClassLoader.

    /**
     * Private helper method
     * 
     * @param directory
     *            The directory to start with
     * @param pckgname
     *            The package name to search for. Will be needed for getting the
     *            Class object.
     * @param classes
     *            if a file isn't loaded but still is in the directory
     * @throws ClassNotFoundException
     */
    private static void checkDirectory(File directory, String pckgname,
            ArrayList<Class<?>> classes) throws ClassNotFoundException {
        File tmpDirectory;
    
        if (directory.exists() && directory.isDirectory()) {
            final String[] files = directory.list();
    
            for (final String file : files) {
                if (file.endsWith(".class")) {
                    try {
                        classes.add(Class.forName(pckgname + '.'
                                + file.substring(0, file.length() - 6)));
                    } catch (final NoClassDefFoundError e) {
                        // do nothing. this class hasn't been found by the
                        // loader, and we don't care.
                    }
                } else if ((tmpDirectory = new File(directory, file))
                        .isDirectory()) {
                    checkDirectory(tmpDirectory, pckgname + "." + file, classes);
                }
            }
        }
    }
    
    /**
     * Private helper method.
     * 
     * @param connection
     *            the connection to the jar
     * @param pckgname
     *            the package name to search for
     * @param classes
     *            the current ArrayList of all classes. This method will simply
     *            add new classes.
     * @throws ClassNotFoundException
     *             if a file isn't loaded but still is in the jar file
     * @throws IOException
     *             if it can't correctly read from the jar file.
     */
    private static void checkJarFile(JarURLConnection connection,
            String pckgname, ArrayList<Class<?>> classes)
            throws ClassNotFoundException, IOException {
        final JarFile jarFile = connection.getJarFile();
        final Enumeration<JarEntry> entries = jarFile.entries();
        String name;
    
        for (JarEntry jarEntry = null; entries.hasMoreElements()
                && ((jarEntry = entries.nextElement()) != null);) {
            name = jarEntry.getName();
    
            if (name.contains(".class")) {
                name = name.substring(0, name.length() - 6).replace('/', '.');
    
                if (name.contains(pckgname)) {
                    classes.add(Class.forName(name));
                }
            }
        }
    }
    
    /**
     * Attempts to list all the classes in the specified package as determined
     * by the context class loader
     * 
     * @param pckgname
     *            the package name to search
     * @return a list of classes that exist within that package
     * @throws ClassNotFoundException
     *             if something went wrong
     */
    public static ArrayList<Class<?>> getClassesForPackage(String pckgname)
            throws ClassNotFoundException {
        final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    
        try {
            final ClassLoader cld = Thread.currentThread()
                    .getContextClassLoader();
    
            if (cld == null)
                throw new ClassNotFoundException("Can't get class loader.");
    
            final Enumeration<URL> resources = cld.getResources(pckgname
                    .replace('.', '/'));
            URLConnection connection;
    
            for (URL url = null; resources.hasMoreElements()
                    && ((url = resources.nextElement()) != null);) {
                try {
                    connection = url.openConnection();
    
                    if (connection instanceof JarURLConnection) {
                        checkJarFile((JarURLConnection) connection, pckgname,
                                classes);
                    } else if (connection instanceof FileURLConnection) {
                        try {
                            checkDirectory(
                                    new File(URLDecoder.decode(url.getPath(),
                                            "UTF-8")), pckgname, classes);
                        } catch (final UnsupportedEncodingException ex) {
                            throw new ClassNotFoundException(
                                    pckgname
                                            + " does not appear to be a valid package (Unsupported encoding)",
                                    ex);
                        }
                    } else
                        throw new ClassNotFoundException(pckgname + " ("
                                + url.getPath()
                                + ") does not appear to be a valid package");
                } catch (final IOException ioex) {
                    throw new ClassNotFoundException(
                            "IOException was thrown when trying to get all resources for "
                                    + pckgname, ioex);
                }
            }
        } catch (final NullPointerException ex) {
            throw new ClassNotFoundException(
                    pckgname
                            + " does not appear to be a valid package (Null pointer exception)",
                    ex);
        } catch (final IOException ioex) {
            throw new ClassNotFoundException(
                    "IOException was thrown when trying to get all resources for "
                            + pckgname, ioex);
        }
    
        return classes;
    }
    

    These three methods provide you with the ability to find all classes in a given package.
    You use it like this:

    getClassesForPackage("package.your.classes.are.in");
    

    The explanation:

    The method first gets the current ClassLoader. It then fetches all resources that contain said package and iterates of these URLs. It then creates a URLConnection and determines what type of URl we have. It can either be a directory (FileURLConnection) or a directory inside a jar or zip file (JarURLConnection). Depending on what type of connection we have two different methods will be called.

    First lets see what happens if it is a FileURLConnection.
    It first checks if the passed File exists and is a directory. If that's the case it checks if it is a class file. If so a Class object will be created and put in the ArrayList. If it is not a class file but is a directory, we simply iterate into it and do the same thing. All other cases/files will be ignored.

    If the URLConnection is a JarURLConnection the other private helper method will be called. This method iterates over all Entries in the zip/jar archive. If one entry is a class file and is inside of the package a Class object will be created and stored in the ArrayList.

    After all resources have been parsed it (the main method) returns the ArrayList containig all classes in the given package, that the current ClassLoader knows about.

    If the process fails at any point a ClassNotFoundException will be thrown containg detailed information about the exact cause.

    0 讨论(0)
  • 2020-11-21 06:09

    Yeah using few API's you can, here is how I like doing it, faced this problem which I was using hibernate core & had to find classes which where annotated with a certain annotation.

    Make these an custom annotation using which you will mark which classes you want to be picked up.

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface EntityToBeScanned {
    
    }
    

    Then mark your class with it like

    @EntityToBeScanned 
    public MyClass{
    
    }
    

    Make this utility class which has the following method

    public class ClassScanner {
    
        public static Set<Class<?>> allFoundClassesAnnotatedWithEntityToBeScanned(){
            Reflections reflections = new Reflections(".*");
            Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(EntityToBeScanned.class);
            return annotated;
        }
    
    }
    

    Call the allFoundClassesAnnotatedWithEntityToBeScanned() method to get a Set of Classes found.

    You will need libs given below

    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
    <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.22.0-CR1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>0.9.10</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题