如何获取jar文件中的类名? [英] How to get names of classes inside a jar file?

查看:243
本文介绍了如何获取jar文件中的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JAR文件,我需要获取这个JAR文件中所有类的名称。我如何做到这一点?

I have a JAR file and I need to get the name of all classes inside this JAR file. How can I do that?

我googled它,看到一些关于JarFile或Java ClassLoader 但我不知道如何做。

I googled it and saw something about JarFile or Java ClassLoader but I have no idea how to do it.

推荐答案

不幸的是,Java不提供一个简单的方法来列出本机JRE中的类。这给了你几个选项:(a)对于任何给定的JAR文件,您可以列出该JAR文件中的条目,找到 .class 文件,然后确定其中Java类每个 .class 文件表示;

Unfortunately, Java doesn't provide an easy way to list classes in the "native" JRE. That leaves you with a couple of options: (a) for any given JAR file, you can list the entries inside that JAR file, find the .class files, and then determine which Java class each .class file represents; or (b) you can use a library that does this for you.

在此选项中,我们将在 / path / to / jar文件中包含的所有Java类列表中填写 classNames jar / file.jar

In this option, we'll fill classNames with the list of all Java classes contained inside a jar file at /path/to/jar/file.jar.

List<String> classNames = new ArrayList<String>();
ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.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()));
    }
}



h2>

Guava



Guava < a>已 ClassPath 至少14.0,我已经使用和喜欢。 ClassPath 的一个好处是,它不会加载它找到的类,这对于扫描大量类非常重要。

Option (b): Using specialized reflections libraries

Guava

Guava has had ClassPath since at least 14.0, which I have used and liked. One nice thing about ClassPath is that it doesn't load the classes it finds, which is important when you're scanning for a large number of classes.

ClassPath cp=ClassPath.from(Thread.currentThread().getContextClassLoader());
for(ClassPath.ClassInfo info : cp.getTopLevelClassesRecurusive("my.package.name")) {
    // Do stuff with classes here...
}



反映



我没有亲自使用反思图书馆,但它似乎很喜欢。在网站上提供了一些很好的例子,像这样快速的方式加载所有类,由任何 JAR文件提供的包,这也可能对您的应用程序有用。

Reflections

I haven't personally used the Reflections library, but it seems well-liked. Some great examples are provided on the website like this quick way to load all the classes in a package provided by any JAR file, which may also be useful for your application.

Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);

这篇关于如何获取jar文件中的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆