读书笔记之java反编译(2)

 有了笔记(1)的阅读经验,来看看下面一点点代码。先从读取class的版本信息开始,应用面向对象的思想

 为什么从版本开始呢因为他位于class二进制文件的顶部

1.定义版本Version类

package readnote; import java.io.DataInputStream; import java.io.IOException; public final class Version { int iMagicNumber; int iMinorVersion; int iMajorVersion; void read(DataInputStream dis) throws IOException { //注意每读取一次,指针自动下移 //每个Class文件的前4个字节被称为它的魔数(magic number) iMagicNumber = dis.readInt(); //Class文件的下面4个字节包含了次、主版本号 iMinorVersion = dis.readUnsignedShort(); iMajorVersion = dis.readUnsignedShort(); } //给出详细的版本信息 public String toString() { String sRetStr; sRetStr = ("Magic number: " + getMagicNumberString() + ", "); sRetStr += ("Minor version: " + iMinorVersion + ", "); sRetStr += ("Major version: " + iMajorVersion + ", "); return sRetStr; } public int getMagicNumberInteger() { return iMagicNumber; } public String getMagicNumberString() { return (Integer.toHexString(iMagicNumber)); } public void setMagicNumberString(String sMagicNumber) { iMagicNumber = Long.valueOf(sMagicNumber, 16).intValue(); } public String getMajorVersionString() { return Integer.toString(iMajorVersion); } public String getMinorVersionString() { return Integer.toString(iMinorVersion); } public void setMajorVersionString(String sVer) { iMajorVersion = Integer.parseInt(sVer); } public void setMinorVersionString(String sVer) { iMinorVersion = Integer.parseInt(sVer); } }

2.定义CalssFile类

package readnote; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ClassFile { public Version version = new Version();//版本信息放到Version 类中 public void read(DataInputStream dis) throws IOException { //第一步读取版本信息 version.read(dis); dis.close(); } public static void main(String[] args) throws IOException { ClassFile classFile = new ClassFile(); DataInputStream dis; dis = new DataInputStream(new BufferedInputStream(new FileInputStream(new File("D:/test/a.class"))));//为什么要用DataInputStream?那就看看java的api吧 classFile.read(dis); System.out.println("版本信息:"+classFile.version.toString()); } }  

版本信息:Magic number: cafebabe, Minor version: 3, Major version: 45,

搞定了,有时间再贴其他的

你可能感兴趣的:(读书笔记之java反编译(2))