获取Classpath中的所有类

ara*_*ash 42 java reflection class

如何CLASSPATH在运行时获取所有可用类的列表?
在Eclipse IDE中,您可以通过按Ctrl+ Shift+ 来完成此操作T.
Java中是否有任何方法可以完成它?

Bal*_*usC 53

你可以通过传递一个空让所有的classpath根StringClassLoader#getResources().

Enumeration<URL> roots = classLoader.getResources("");
Run Code Online (Sandbox Code Playgroud)

您可以构建一个File基于URL如下的内容:

File root = new File(url.getPath());
Run Code Online (Sandbox Code Playgroud)

您可以使用File#listFiles()获取给定目录中所有文件的列表:

for (File file : root.listFiles()) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

您可以使用标准java.io.File方法检查它是否是目录和/或获取文件名.

if (file.isDirectory()) {
    // Loop through its listFiles() recursively.
} else {
    String name = file.getName();
    // Check if it's a .class file or a .jar file and handle accordingly.
}
Run Code Online (Sandbox Code Playgroud)

根据唯一的功能要求,我猜想Reflections库更符合您的需求.

  • "classpath根"是什么意思?我注意到`classLoader.getResources("")`只返回类路径上的一个或两个目录,那些似乎包含我自己写的.class文件(而不是第三方包中的那些). (3认同)

And*_*ndy 20

这就是我写的内容.如果你对类路径做任何奇怪的事情,我肯定它不会得到一切,但它似乎对我有用.请注意,它实际上并不加载类,它只返回它们的名称.这样它就不会将所有类加载到内存中,并且因为如果在错误的时间加载,我公司代码库中的某些类会导致初始化错误...

public interface Visitor<T> {
    /**
     * @return {@code true} if the algorithm should visit more results,
     * {@code false} if it should terminate now.
     */
    public boolean visit(T t);
}

public class ClassFinder {
    public static void findClasses(Visitor<String> visitor) {
        String classpath = System.getProperty("java.class.path");
        String[] paths = classpath.split(System.getProperty("path.separator"));

        String javaHome = System.getProperty("java.home");
        File file = new File(javaHome + File.separator + "lib");
        if (file.exists()) {
            findClasses(file, file, true, visitor);
        }

        for (String path : paths) {
            file = new File(path);
            if (file.exists()) {
                findClasses(file, file, false, visitor);
            }
        }
    }

    private static boolean findClasses(File root, File file, boolean includeJars, Visitor<String> visitor) {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                if (!findClasses(root, child, includeJars, visitor)) {
                    return false;
                }
            }
        } else {
            if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file);
                } catch (Exception ex) {

                }
                if (jar != null) {
                    Enumeration<JarEntry> entries = jar.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        int extIndex = name.lastIndexOf(".class");
                        if (extIndex > 0) {
                            if (!visitor.visit(name.substring(0, extIndex).replace("/", "."))) {
                                return false;
                            }
                        }
                    }
                }
            }
            else if (file.getName().toLowerCase().endsWith(".class")) {
                if (!visitor.visit(createClassName(root, file))) {
                    return false;
                }
            }
        }

        return true;
    }

    private static String createClassName(File root, File file) {
        StringBuffer sb = new StringBuffer();
        String fileName = file.getName();
        sb.append(fileName.substring(0, fileName.lastIndexOf(".class")));
        file = file.getParentFile();
        while (file != null && !file.equals(root)) {
            sb.insert(0, '.').insert(0, file.getName());
            file = file.getParentFile();
        }
        return sb.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它:

ClassFinder.findClasses(new Visitor<String>() {
    @Override
    public boolean visit(String clazz) {
        System.out.println(clazz)
        return true; // return false if you don't want to see any more classes
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用String [] paths = classpath.split(System.getProperty("path.separator")); 否则它不适用于Linux (2认同)

Mat*_*ise 7

您可以使用com.google.common.reflectGuava库中的实用程序类.例如,获取特定包中的所有类:

    ClassLoader cl = getClass().getClassLoader();
    Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(cl).getTopLevelClassesRecursive("com.mycompany.mypackage");
Run Code Online (Sandbox Code Playgroud)

这是简明扼要的,但是与其他答案描述的相同的警告仍然适用,即它通常只能找到由"标准"ClassLoader加载的类,例如URLClassLoader.