读取 Java .class 文件

发布于 2024-10-14 01:57:04 字数 263 浏览 5 评论 0原文

我想编写一个工具,使用已编译的 .class 文件作为输入来生成一些代码。具体来说,我想从这个类文件中读取:

  • 带注释的方法 带注释
  • 的方法参数

输入类文件可能会引用不在工具类路径中的几种类型。没关系,我不需要对它们做任何事情,只需要将完全限定的类型名称读取为字符串。我确实需要从注释中获取一些信息,但它们将位于工具的类路径中。

是否有一个库可供我用于此目的?如果 API 有点像反射 API 那就太好了,但事实并非如此。

I want to write a tool which generates some code using a compiled .class file as input. Specifically, I want to read from this class file:

  • Methods, with annotations
  • Method parameters, with annotations

The input class file will likely refer to several types that are not in the tool's classpath. This is ok, I don't need to do anything with them, just need to read fully qualified type names as strings. I do need to get some information from the annotations, but they will be in the tool's classpath.

Is there a library which I can use for this purpose? It would be nice if the API was a bit like the reflection API, but it doesn't have to be.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

久而酒知 2024-10-21 01:57:04

ASM http://asm.ow2.org/ 允许您从文件/输入流中读取类,而无需类加载它。它允许您查看运行时未加载的注释。它还可以用于修改类字节码/注释/方法等。

ASM http://asm.ow2.org/ allows you to read a class from a file/input stream without class loading it. It allows you to see annotations which are not loaded at runtime. It can also be used to modify the class byte code/annotations/method etc.

苦妄 2024-10-21 01:57:04

JDK 中可能包含 javap 工具已经做了你想做的事。

The javap tool included with the JDK probably already does what you're after.

蒲公英的约定 2024-10-21 01:57:04

您需要查看两件事Reflection API反编译器

You need to look at two things Reflection API and Decompiler

羁绊已千年 2024-10-21 01:57:04

我认为你可以使用 spring 类扫描。

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
    System.out.printf("Component: %s\n", component.getBeanClassName());
}

有关更多信息,您可以查看 spring 文档

I think you could use spring class scanning.

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
    System.out.printf("Component: %s\n", component.getBeanClassName());
}

for more information you can look into spring docs

我纯我任性 2024-10-21 01:57:04

我正在使用 asm 来查找所有方法。

I'm using asm for finding out all the methods.

榕城若虚 2024-10-21 01:57:04

如果您有权生成 .class 文件,则 Reflection API 应该能够提供帮助。

If you have access to generating the .class file then the Reflection API should be able to help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文