Table of Contents
Class file
How to parse the various data items that make up the
代码实现
Home Java javaTutorial Sharing the powerful code to implement a Java Class parser

Sharing the powerful code to implement a Java Class parser

Mar 18, 2017 am 10:41 AM

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

}
Copy after login

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

Class

file and is used to store all constant information, including numeric and string constants, class names, interface names, field names and method names, etc. . JavaThe 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, if constantPoolCount Equal to 47, then there are 46 constants in the constant pool.

  • The index range of the constant pool starts from
  • 1

    . For example, if constantPoolCount is equal to 47, then the index range of the constant pool The index range is 1~46. The designer left the 0 item empty to express "not referencing any constant pool item". The structure of the

  • CONSTANT_Utf8_info

    type constant contains the tag and u2 types of the u1 type. The length and bytes composed of length u1 types, this length bytes of continuous data is A string encoded using MUTF-8 (Modified UTF-8). MUTF-8 is not compatible with UTF-8. There are two main differences: First, the null character will be encoded into 2 Bytes (0xC0 and 0x80); second, the supplementary characters are split into surrogate pairs and encoded separately according to UTF-16. The relevant details can be seen here ( variant UTF-8). </li></ul><p>属性表用于描述某些场景专有的信息,<code>Class文件、字段表和方法表都有相应的属性表集合。Java虚拟机规范定义了多种属性,ClassAnalyzer目前实现了对常用属性的解析。和常量类型的数据项不同,属性并没有一个tag来标识属性的类型,但是每个属性都包含有一个u2类型的attribute_name_indexattribute_name_index指向常量池中的一个CONSTANT_Utf8_info类型的常量,该常量包含着属性的名称。在解析属性时,ClassAnalyzer正是通过attribute_name_index指向的常量对应的属性名称来得知属性的类型。

    字段表用于描述类或者接口中声明的变量,字段包括类级变量以及实例级变量。字段表的结构包含一个u2类型的access_flags、一个u2类型的name_index、一个u2类型的descriptor_index、一个u2类型的attributes_countattributes_countattribute_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属性中,codeLengthcode分别用于存储字节码长度和字节码指令,每条指令即一个字节(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

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 vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

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.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

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

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

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.

See all articles