Home Java javaTutorial Example of method to implement Class parser in Java

Example of method to implement Class parser in Java

Sep 15, 2017 am 10:16 AM
class java method

This article mainly introduces examples of Java Class parser implementation methods through the analysis of class files. It has certain reference value and friends in need can learn about it.

Recently I am writing a private project called ClassAnalyzer. The purpose of ClassAnalyzer is to give us an in-depth understanding of the design and structure of Java Class files. The main 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 a carrier of class or interface information, each Class file completely defines a class. In order to make Java programs "write once and run anywhere", the Java virtual machine specification has strict regulations on Class files. The basic data unit that constitutes a Class file is bytes. There are no separators between these bytes. This makes the content stored in the entire Class file almost all necessary data for program operation. Data that cannot be represented by a single byte is represented by multiple represented by 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. There are only two data types in this pseudo-structure: unsigned numbers and tables. The Java virtual machine specification defines u1, u2, u4 and u8 to represent unsigned numbers of 1 byte, 2 bytes, 4 bytes and 8 bytes respectively. Unsigned numbers can be used to describe numbers and indexes. A reference, quantity, or string. A table is a composite data type composed of multiple unsigned numbers or other tables as data items. The table is used to describe data with a hierarchical composite structure, so the entire Class file is essentially a table. In ClassAnalyzer, byte, short, int and long correspond to u1, u2, u4 and u8 data types respectively. 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 and the version of the Class file Data items, access flags, class indexes, and parent class indexes all 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, there are mainly four parts that need to be handled flexibly: 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, method names, etc. The Java virtual machine specification defines multiple constant types, each of which 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 u1 type tag.


The constant pool size (constantPoolCount) given in the header is 1 larger than the actual value. For example, if constantPoolCount is 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 equals 47, then the index range of the constant pool is 1~46. The designer's purpose of leaving item 0 empty is to express "not referencing any constant pool item".


The structure of the CONSTANT_Utf8_info constant contains a tag of type u1, a length of type u2 and length bytes of type u1. The continuous data of length bytes is a MUTF-8 (Modified UTF-8) encoded string. 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 found here (variant UTF-8).


Attribute tables are used to describe information specific to certain scenarios. Class files, field tables, and method tables all have corresponding attribute table sets. The Java virtual machine specification defines a variety of attributes, and ClassAnalyzer currently implements the analysis of commonly used attributes. Unlike data items of constant type, attributes do not have a tag to identify the type of the attribute, but each attribute contains an attribute_name_index of type u2. Attribute_name_index points to a constant of type CONSTANT_Utf8_info in the constant pool, which contains the attribute's name. When parsing attributes, ClassAnalyzer knows the type of the attribute through the attribute name corresponding to the constant pointed to by attribute_name_index.


Field table is used to describe variables declared in a class or interface. Fields include class-level variables and instance-level variables. The structure of the field table includes a u2 type access_flags, a u2 type name_index, a u2 type descriptor_index, a u2 type attributes_count and attributes_count attributes_info type attributes. We have already introduced the parsing of attribute tables. The parsing method of attributes is consistent with the parsing method of attribute tables.


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 Example of method to implement Class parser in Java. 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)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

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

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 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.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles