Can you find all classes in a package using reflection?

前端 未结 27 2213
不知归路
不知归路 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 05:50

    Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.

    However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.

    If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.

    The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

    Addendum: The Reflections Library will allow you to look up classes in the current classpath. It can be used to get all classes in a package:

     Reflections reflections = new Reflections("my.project.prefix");
    
     Set<Class<? extends Object>> allClasses = 
         reflections.getSubTypesOf(Object.class);
    
    0 讨论(0)
  • 2020-11-21 05:50

    Provided you are not using any dynamic class loaders you can search the classpath and for each entry search the directory or JAR file.

    0 讨论(0)
  • 2020-11-21 05:51

    What about this:

    public static List<Class<?>> getClassesForPackage(final String pkgName) throws IOException, URISyntaxException {
        final String pkgPath = pkgName.replace('.', '/');
        final URI pkg = Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource(pkgPath)).toURI();
        final ArrayList<Class<?>> allClasses = new ArrayList<Class<?>>();
    
        Path root;
        if (pkg.toString().startsWith("jar:")) {
            try {
                root = FileSystems.getFileSystem(pkg).getPath(pkgPath);
            } catch (final FileSystemNotFoundException e) {
                root = FileSystems.newFileSystem(pkg, Collections.emptyMap()).getPath(pkgPath);
            }
        } else {
            root = Paths.get(pkg);
        }
    
        final String extension = ".class";
        try (final Stream<Path> allPaths = Files.walk(root)) {
            allPaths.filter(Files::isRegularFile).forEach(file -> {
                try {
                    final String path = file.toString().replace('/', '.');
                    final String name = path.substring(path.indexOf(pkgName), path.length() - extension.length());
                    allClasses.add(Class.forName(name));
                } catch (final ClassNotFoundException | StringIndexOutOfBoundsException ignored) {
                }
            });
        }
        return allClasses;
    }
    

    You can then overload the function:

    public static List<Class<?>> getClassesForPackage(final Package pkg) throws IOException, URISyntaxException {
        return getClassesForPackage(pkg.getName());
    }
    

    If you need to test it:

    public static void main(final String[] argv) throws IOException, URISyntaxException {
        for (final Class<?> cls : getClassesForPackage("my.package")) {
            System.out.println(cls);
        }
        for (final Class<?> cls : getClassesForPackage(MyClass.class.getPackage())) {
            System.out.println(cls);
        }
    }
    

    If your IDE does not have import helper:

    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.nio.file.FileSystemNotFoundException;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Objects;
    import java.util.stream.Stream;
    

    It works:

    • from your IDE

    • for a JAR file

    • without external dependencies

    0 讨论(0)
  • 2020-11-21 05:53

    Here's how I do it. I scan all the subfolders (sub-packages) and I don't try to load anonymous classes:

       /**
       * Attempts to list all the classes in the specified package as determined
       * by the context class loader, recursively, avoiding anonymous classes
       * 
       * @param pckgname
       *            the package name to search
       * @return a list of classes that exist within that package
       * @throws ClassNotFoundException
       *             if something went wrong
       */
      private static List<Class> getClassesForPackage(String pckgname) throws ClassNotFoundException {
          // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
          ArrayList<File> directories = new ArrayList<File>();
          String packageToPath = pckgname.replace('.', '/');
          try {
              ClassLoader cld = Thread.currentThread().getContextClassLoader();
              if (cld == null) {
                  throw new ClassNotFoundException("Can't get class loader.");
              }
    
              // Ask for all resources for the packageToPath
              Enumeration<URL> resources = cld.getResources(packageToPath);
              while (resources.hasMoreElements()) {
                  directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
              }
          } catch (NullPointerException x) {
              throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Null pointer exception)");
          } catch (UnsupportedEncodingException encex) {
              throw new ClassNotFoundException(pckgname + " does not appear to be a valid package (Unsupported encoding)");
          } catch (IOException ioex) {
              throw new ClassNotFoundException("IOException was thrown when trying to get all resources for " + pckgname);
          }
    
          ArrayList<Class> classes = new ArrayList<Class>();
          // For every directoryFile identified capture all the .class files
          while (!directories.isEmpty()){
              File directoryFile  = directories.remove(0);             
              if (directoryFile.exists()) {
                  // Get the list of the files contained in the package
                  File[] files = directoryFile.listFiles();
    
                  for (File file : files) {
                      // we are only interested in .class files
                      if ((file.getName().endsWith(".class")) && (!file.getName().contains("$"))) {
                          // removes the .class extension
                          int index = directoryFile.getPath().indexOf(packageToPath);
                          String packagePrefix = directoryFile.getPath().substring(index).replace('/', '.');;                          
                        try {                  
                          String className = packagePrefix + '.' + file.getName().substring(0, file.getName().length() - 6);                            
                          classes.add(Class.forName(className));                                
                        } catch (NoClassDefFoundError e)
                        {
                          // do nothing. this class hasn't been found by the loader, and we don't care.
                        }
                      } else if (file.isDirectory()){ // If we got to a subdirectory
                          directories.add(new File(file.getPath()));                          
                      }
                  }
              } else {
                  throw new ClassNotFoundException(pckgname + " (" + directoryFile.getPath() + ") does not appear to be a valid package");
              }
          }
          return classes;
      }  
    
    0 讨论(0)
  • 2020-11-21 05:54

    You could use this method1 that uses the ClassLoader.

    /**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @param packageName The base package
     * @return The classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    private static Class[] getClasses(String packageName)
            throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes.toArray(new Class[classes.size()]);
    }
    
    /**
     * 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
     * @throws ClassNotFoundException
     */
    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
    

    __________
    1 This method was taken originally from http://snippets.dzone.com/posts/show/4831, which was archived by the Internet Archive, as linked to now. The snippet is also available at https://dzone.com/articles/get-all-classes-within-package.

    0 讨论(0)
  • 2020-11-21 05:55

    Aleksander Blomskøld's solution did not work for me for parameterized tests @RunWith(Parameterized.class) when using Maven. The tests were named correctly and also where found but not executed:

    -------------------------------------------------------
    T E S T S
    -------------------------------------------------------
    Running some.properly.named.test.run.with.maven.SomeTest
    Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.123 sec
    

    A similar issue has been reported here.

    In my case @Parameters is creating instances of each class in a package. The tests worked well when run locally in the IDE. However, when running Maven no classes where found with Aleksander Blomskøld's solution.

    I did make it work with the following snipped which was inspired by David Pärsson's comment on Aleksander Blomskøld's answer:

    Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
                .addUrls(ClasspathHelper.forJavaClassPath()) 
                .filterInputsBy(new FilterBuilder()
                .include(FilterBuilder.prefix(basePackage))));
    
    Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class);
    
    0 讨论(0)
提交回复
热议问题