简体   繁体   English

类文件解析器

[英]Class file parser

I have an assignment where i need to write a Java program that parses a .class file and retrieves things like :我有一个作业,我需要编写一个解析 .class 文件并检索以下内容的 Java 程序:

1.name of the .java file 1.java文件名

2.implemented interfaces 2.实现的接口

3.variables 3.变量

4.constructors 4.构造函数

5.methods 5.方法

I don't have any ideeas where to begin from?我没有任何想法从哪里开始? For example,what kind of Data I/O structure should I use?例如,我应该使用什么样的数据 I/O 结构?

You don't need any external library, just use java.lang.Class .您不需要任何外部库,只需使用java.lang.Class Write the name of your class:写下你的班级名称:

[NameOfMyClass].class.getDeclaredFields();
[NameOfMyClass].class.getDeclaredConstructors();
[NameOfMyClass].class.getDeclaredMethods();

It's the same for interfaces and many other attributes.接口和许多其他属性也是如此。

There are already several libraries for classfile parsing out there.已经有几个用于类文件解析的库。 Objectweb ASM is the most popular. Objectweb ASM 是最受欢迎的。

If you have to do it from scratch, that I'd recommend starting by the JVM specification , which explains the binary layout of classfiles in detail.如果您必须从头开始,我建议您从JVM 规范开始,其中详细解释了类文件的二进制布局。 After that, parsing is just a simple matter of programming.之后,解析只是一个简单的编程问题。 I've written a classfile parser before, it's not that hard.我以前写过一个类文件解析器,没那么难。

You can use Java Reflection.您可以使用 Java 反射。 Here is a good tutorial -->这是一个很好的教程-->

Java Reflection Tutorial Java 反射教程

  • You can you ClassParser which is available in Apache commons library.您可以使用 Apache 公共库中提供的ClassParser you can read the Javadoc here .你可以在这里阅读 Javadoc。 You can download apache commons fromhere你可以从这里下载 apache commons
  • You can also use Java reflection API which provides method such as getDeclaredFileds , getDeclaredMethods etc.您还可以使用 Java 反射 API,它提供诸如getDeclaredFiledsgetDeclaredMethods等方法。

OpenJDK actually comes with an API that lets you parse and manipulate class files programmatically that most programmers don't know about. OpenJDK 实际上带有一个 API,可以让您以编程方式解析和操作大多数程序员不知道的类文件。 It is located at the package com.sun.org.apache.bcel.internal .它位于com.sun.org.apache.bcel.internal包中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM