首页 > 学院 > 开发设计 > 正文

Class文件详解 (1)

2019-11-18 14:50:50
字体:
来源:转载
供稿:网友

  我们都知道,java编译器负责将.java文件编译成.class文件,class文件存储的是java字节码,与.java文件无关(只要你愿意写一个编译器,也可以将别的语言写的源代码编译成.class文件),本文预备具体解剖class文件的内部结构,并且把class文件结构读取并显示出来。

Class文件的格式由JVM规范规定,一共有以下部分:
1. magic number,必须是0xCAFEBABE,用于快速识别是否是一个class文件。
2. version,包括major和minor,假如版本号超过了JVM的识别范围,JVM将拒绝执行。
3. constant pool,常量池,存放所有用到的常量。
4. access flag,定义类的访问权限。
5. this class和super class,指示如何找到this class和super class。
6. interfaces,存放所有interfaces。
7. fields,存放所有fields。
8. methods,存放所有methods。
9. attributes,存放所有attributes。

先写一个Test.java:

package example.test;

public final class TestClass {
    public int id = 1234567;
    public void test() {}
}

然后编译,放在C:/example/test/Test.class。

我们用Java来读取和分析class,ClassAnalyzer的功能便是读取Test.class,分析结构,然后显示出来:

package classfile.format;

import java.io.*;

public class ClassAnalyzer {

    public static void main(String[] args) {
        DataInputStream input = null;
        try {
            input = new DataInputStream(new BufferedInputStream(new FileInputStream(
                "C://example//test//TestClass.class"
            )));
            analyze(input);
        }
        catch(Exception e) {
            System.out.PRintln("Analyze failed!");
        }
        finally {
            try { input.close(); } catch(Exception e) {}
        }
    }

    public static void analyze(DataInputStream input) throws IOException {
        // read magic number:
        int magic = input.readInt();
        if(magic==0xCAFEBABE)
            System.out.println("magic number = 0xCAFEBABE");
        else
            throw new RuntimeException("Invalid magic number!");
        // read minor version and major version:
        short minor_ver = input.readShort();
        short major_ver = input.readShort();
        System.out.println("Version = " + major_ver + "." + minor_ver);
        // read constant pool:
        short const_pool_count = input.readShort();
        System.out.println("constant pool size = " + const_pool_count);
        // read each constant:
        for(int i=1; i<const_pool_count; i++) {
            analyzeConstant(input, i);
        }
    }



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表