---
title: "读书笔记：java的class文件格式分析（一）"
author: "ZangXT"
date: "2009-03-21T17:45:00Z"
tags: ["Access", "Java", "读书"]
categories: ["编程语言"]
slug: "java-class"
draft: false
lastmod: "2010-04-04T10:16:17Z"
id: 421515
url: "https://zangxt.iteye.com/blog/421515"
---

阅读Java Virtual Machine Specification中的第四章，理解Java的class文件格式。

> class文件由8位的字节流组成。
> 
> The ClassFile Structure
> 
> ClassFile{
> 
> u4 magic;
> 
> u2 minor\_version;
> 
> u2 major\_version;
> 
> u2 constant\_pool\_count;
> 
> cp\_info constant\_pool\[constant\_pool\_count-1];
> 
> u2 access\_flags;
> 
> u2 this\_class;
> 
> u2 interfaces\_count;
> 
> u2 interfaces\[interfaces\_count];
> 
> u2 fields\_count;
> 
> field\_info fields\[fields\_count];
> 
> u2 methods\_count;
> 
> method\_info methods\[methods\_count];
> 
> u2 attributes\_count;
> 
> attribute\_info attributes\[attrributes\_count];
> 
> }
> 
> 说明：u2表示无符号2字节量，u4表示无符号4字节量。
> 
> 各字段的说明：
> 
> magic
> 
> 一般二进制文件中都有magic number这一项，这个数说明该文件是一个class文件，它的值是0xcAFEBABE。
> 
> minor\_version,major\_version
> 
> class文件的版本号。
> 
> constant\_pool\_count
> 
> 常量池表中项目数加1得到。从后面的cp\_info constant\_pool\[constant\_pool\_count-1];也容易理解这个值的意思。
> 
> cp\_info constant\_pool\[]
> 
> 存储该class文件中使用到的常量信息。
> 
> access\_flag
> 
> 说明该class文件的访问权限和相关属性，通过位掩码来设定。
> 
> Flag Name 值 解释 ACC\_PUBLIC 0x0001 public ACC\_FINAL 0x0010 final ACC\_SUPER 0x0020 跟调用invokespecial指令时的处理有关 ACC\_INTERFACE 0x0200 这是个接口 ACC\_ABSTRACT 0x0400 abastract ACC\_SYNTHETIC 0x1000 没有在源代码中出现，该类是编译器生成的 ACC\_ANNOTATION 0x2000 注解类型 ACC\_ENUM 0x4000 枚举类型
> 
> 这些属性都很容易理解，比如我们定义一个类public final Test{},则Test.class的access\_flag中，ACC\_PUBLIC和ACC\_FINAL是置位的，而ACC\_INTERFACE一项肯定是0。很多类似的组合规则倒是容易自己总结出来，比如如果ACC\_INTERFACE置位了，那肯定ACC\_ABSTRACT也是置位的，因为接口肯定是抽象的；等等，诸如此类。
> 
> 画一个具体的位示意图表示：
> 
> [![image](http://p.blog.csdn.net/images/p_blog_csdn_net/zangxt/526356/o_image_thumb.png)](http://p.blog.csdn.net/images/p_blog_csdn_net/zangxt/526356/o_image_2.png)
> 
> this\_class
> 
> 一个下标，指向常量池表中代表当前类的Constant\_Class\_info。
> 
> super\_class
> 
> 为0，或者为一个下标，指向常量池中代表其父类的Constant\_Class\_info。如果这个值为0，那么当前类肯定是Object类。如果当前类是一个接口，该下标指向的是Object类的描述信息。
> 
> interface\_count
> 
> 该类实现的接口数，或者该接口实现的超接口数。
> 
> interfaces\[]
> 
> 具体的接口信息，每一项都是常量池表中的一个下标，指向表示接口的Constant\_Class\_info。
> 
> 后面几个依次是字段（field），方法（methods）和属性的描述，不再赘述，

> 下面具体的分析一个class文件。源文件很简单：
> 
> public class Test{  
> public static void main(String\[] args){  
> System.out.println("Hello World!");  
> }  
> }
> 
> 编译，得到Test.class文件，使用WinHex打开。
> 
> [![image](http://p.blog.csdn.net/images/p_blog_csdn_net/zangxt/526356/o_image_thumb_1.png)](http://p.blog.csdn.net/images/p_blog_csdn_net/zangxt/526356/o_image_4.png)
> 
> 前4个字节是magic部分，内容为0xCAFEBABE;随后的4个字节是class文件的版本号，这里主版本号是0x0032，也就是50，这是使用jdk1.6编译出的class文件。再后面的2个字节是常量池表的大小信息，0x001D，也就是29，说明常量池表中一共有28项。为了方便观察，可以使用javap -verbose Test得到的结果和当前的二进制文件进行对比。
> 
> 入门到此，以后继续。