Sharing the powerful code to implement a Java Class parser
Recently I am writing a private project called ClassAnalyzer
. The purpose of ClassAnalyzer
is to allow us to analyze <span class="wp_keywordlink">Java Class</span>
files. Design and structure can have an in-depth understanding. The main body framework and basic functions have been completed, and some detailed functions will be added in the future. In fact, JDK
already provides the command line tool javap
to decompile Class
files, but this article will clarify my idea of implementing the parser.
Class file
As the carrier of class or interface information, each Class
file completely defines a class. In order to make Java
programs "write once and run everywhere", the Java virtual machine specification has strict regulations on Class
files. The basic data unit that constitutes the Class
file is bytes, and there are no delimiters between these bytes. This makes almost all the content stored in the entire Class
file necessary for the program to run. Data that cannot be represented by a single byte is represented by multiple consecutive bytes.
According to the Java
virtual machine specification, the Class
file uses a pseudo structure similar to the C
language structure to store data. This pseudo structure There are only two data types in the structure: unsigned numbers and tables. Java
The virtual machine specification defines u1
, u2
, u4
and u8
to represent 1 respectively. Unsigned numbers of
bytes, 2
bytes, 4
bytes and 8
bytes, unsigned numbers can be used Description number, indexreference, quantity value or string. A table is a conforming data type composed of multiple unsigned numbers or other tables as data items. The table is used to describe structured data with hierarchical relationships, so the entire Class
file is essentially a table. In ClassAnalyzer
u1
, u2
, u4
and u8
respectively correspond to byte
, short
, int
and long
, the Class
file is described as the following Java
class.
public class ClassFile { public U4 magic; // magic public U2 minorVersion; // minor_version public U2 majorVersion; // major_version public U2 constantPoolCount; // constant_pool_count public ConstantPoolInfo[] cpInfo; // cp_info public U2 accessFlags; // access_flags public U2 thisClass; // this_class public U2 superClass; // super_class public U2 interfacesCount; // interfaces_count public U2[] interfaces; // interfaces public U2 fieldsCount; // fields_count public FieldInfo[] fields; // fields public U2 methodsCount; // methods_count public MethodInfo[] methods; // methods public U2 attributesCount; // attributes_count public BasicAttributeInfo[] attributes; // attributes }
How to parse the various data items that make up the
Class file, such as the magic number, the version of the Class
file, and other data items, access flags , class index, parent class index, they occupy a fixed number of bytes in each Class
file, and only the corresponding number of bytes need to be read during parsing. In addition, the main parts that need to be handled flexibly include 4
: constant pool, field table collection, method table collection and attribute table collection. Fields and methods can have their own attributes, and Class
itself also has corresponding attributes. Therefore, parsing the field table collection and method table collection also includes the parsing of the attribute table. The constant pool occupies a large part of the data in the
file and is used to store all constant information, including numeric and string constants, class names, interface names, field names and method names, etc. . Java
The virtual machine specification defines multiple constant types, and each constant type has its own structure. The constant pool itself is a table, and there are several points to pay attention to when parsing it.
- Each constant type is identified by a tag of type
- u1
.
The constant pool size ( - constantPoolCount
) given in the header is
1
larger than the actual size, for example, ifconstantPoolCount
Equal to47
, then there are46
constants in the constant pool. The index range of the constant pool starts from - 1
. For example, if
constantPoolCount
is equal to47
, then the index range of the constant pool The index range is1~46
. The designer left the0
item empty to express "not referencing any constant pool item". The structure of the - CONSTANT_Utf8_info
type constant contains the
tag
andu2
types of theu1
type. Thelength
andbytes
composed oflength
u1
types, thislength
bytes of continuous data is A string encoded usingMUTF-8
(Modified UTF-8)
.MUTF-8
is not compatible withUTF-8
. There are two main differences: First, thenull
character will be encoded into2
Bytes (0xC0
and0x80
); second, the supplementary characters are split into surrogate pairs and encoded separately according toUTF-16
. The relevant details can be seen here ( variant UTF-8).</li></ul><p>属性表用于描述某些场景专有的信息,<code>Class
文件、字段表和方法表都有相应的属性表集合。Java
虚拟机规范定义了多种属性,ClassAnalyzer
目前实现了对常用属性的解析。和常量类型的数据项不同,属性并没有一个tag
来标识属性的类型,但是每个属性都包含有一个u2
类型的attribute_name_index
,attribute_name_index
指向常量池中的一个CONSTANT_Utf8_info
类型的常量,该常量包含着属性的名称。在解析属性时,ClassAnalyzer
正是通过attribute_name_index
指向的常量对应的属性名称来得知属性的类型。字段表用于描述类或者接口中声明的变量,字段包括类级变量以及实例级变量。字段表的结构包含一个
u2
类型的access_flags
、一个u2
类型的name_index
、一个u2
类型的descriptor_index
、一个u2
类型的attributes_count
和attributes_count
个attribute_info
类型的attributes
。我们已经介绍了属性表的解析,attributes
的解析方式与属性表的解析方式一致。Class
的文件方法表采用了和字段表相同的存储格式,只是access_flags
对应的含义有所不同。方法表包含着一个重要的属性:Code
属性。Code
属性存储了Java
代码编译成的字节码指令,在ClassAnalyzer
中,Code
对应的Java
类如下所示(仅列出了类属性)。public class Code extends BasicAttributeInfo { private short maxStack; private short maxLocals; private long codeLength; private byte[] code; private short exceptionTableLength; private ExceptionInfo[] exceptionTable; private short attributesCount; private BasicAttributeInfo[] attributes; ... private class ExceptionInfo { public short startPc; public short endPc; public short handlerPc; public short catchType; ... } }
Copy after login在
Code
属性中,codeLength
和code
分别用于存储字节码长度和字节码指令,每条指令即一个字节(u1
类型)。在虚拟机执行时,通过读取code
中的一个个字节码,并将字节码翻译成相应的指令。另外,虽然codeLength
是一个u4
类型的值,但是实际上一个方法不允许超过65535
条字节码指令。代码实现
ClassAnalyzer
的源码已放在了GitHub上。在ClassAnalyzer
的README中,我以一个类的Class
文件为例,对该Class
文件的每个字节进行了分析,希望对大家的理解有所帮助。The above is the detailed content of Sharing the powerful code to implement a Java Class parser. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
