获取包中的类文件的阵列中的Java [复制](Get a array of class files

2019-06-25 05:32发布

这个问题已经在这里有一个答案:

  • 你可以在使用反射包中的所有类? 23个回答

我需要一个类[]包含在Java中我的源码包之一的所有类文件。

我无法找到一个标准的方法来做到这一点在一杆。 如果有人可以编写一个函数来获取该清单将是很有益的。

Class[] myClasses = yourfunction();  // Return a list of class inside a source package in the currently working project in java

Answer 1:

我能解决使用普通文件I / O和搜索机制这个问题。 您可以检查答案贴在这里。

private static List<Class> getClassesForPackage(Package pkg) {
    String pkgname = pkg.getName();

    List<Class> classes = new ArrayList<Class>();

    // Get a File object for the package
    File directory = null;
    String fullPath;
    String relPath = pkgname.replace('.', '/');

    //System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath);

    URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);

    //System.out.println("ClassDiscovery: Resource = " + resource);
    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    fullPath = resource.getFile();
    //System.out.println("ClassDiscovery: FullPath = " + resource);

    try {
        directory = new File(resource.toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...", e);
    } catch (IllegalArgumentException e) {
        directory = null;
    }
    //System.out.println("ClassDiscovery: Directory = " + directory);

    if (directory != null && directory.exists()) {

        // Get the list of the files contained in the package
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {

            // we are only interested in .class files
            if (files[i].endsWith(".class")) {

                // removes the .class extension
                String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                //System.out.println("ClassDiscovery: className = " + className);

                try {
                    classes.add(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("ClassNotFoundException loading " + className);
                }
            }
        }
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            JarFile jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {

                    //System.out.println("ClassDiscovery: JarEntry: " + entryName);
                    String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                    //System.out.println("ClassDiscovery: className = " + className);
                    try {
                        classes.add(Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
        }
    }
    return classes;
}


Answer 2:

没有尝试这对所有的虚拟机,但是在最近的Oracle虚拟机有一个较短的方式:

Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("package/name/with/slashes/instead/dots");
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        System.out.println(url);
        System.out.println(new Scanner((InputStream) url.getContent()).useDelimiter("\\A").next());
    }

这将打印出资源的名称在包装,所以你可以使用getResource(...)在他们身上。 呼叫url.getContent()将返回的实例sun.net.www.content.text.PlainTextInputStream这是一个虚拟机的具体类。



文章来源: Get a array of class files inside a package in Java [duplicate]
标签: java class