【问题标题】:Java: how to get the full list of classes avaliable in runtime? [duplicate]Java:如何获取运行时可用类的完整列表? [复制]
【发布时间】:2019-02-01 10:06:11
【问题描述】:

我正在寻找一种方法来获取 Java 运行时中可用的所有类和包的完整列表。

我发现许多解决方案只打印“.jars”列表或包含类路径中加载的类的文件夹,但这对我来说还不够,我需要可用类的列表。

如何做到这一点?

【问题讨论】:

    标签: java classpath classloader


    【解决方案1】:

    下面的代码将为您提供作为路径传递的外部 jar 的类名列表(完全限定)

    package Sample;
    
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.zip.ZipEntry;
        import java.util.zip.ZipInputStream;
    
        public class Sample {
            public static void main(String[] args) throws IOException {
                List<String> classNames = new ArrayList<String>();
                ZipInputStream zip = new ZipInputStream(new FileInputStream("C:\\Users\\foo\\Desktop\\foo.solutions.jar"));
                for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
                    if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
                        // This ZipEntry represents a class. Now, what class does it represent?
                        String className = entry.getName().replace('/', '.'); // including ".class"
                        classNames.add(className.substring(0, className.length() - ".class".length()));
                    }
                }
                System.out.println(classNames);
            }
        }
    

    【讨论】:

    • 它对你有用吗?
    • 您确实意识到这只会读取 jar 中的类文件。这并不完全意味着它们已加载。
    猜你喜欢
    • 2011-03-29
    • 2015-09-12
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2010-09-16
    • 2021-11-15
    相关资源
    最近更新 更多