java修改class文件
最近因为工作需要修改class文件中一个变量的值,特此记录
1、首先使用bytecode viewer打开class文件(下载地址:链接:https://pan.baidu.com/s/1fo6SWTfoNZ5usEQU_R4JmA 提取码:zecz)
2、找到要修改的变量所在的地址
3、创建一个java工程、并且将jclasslib.jar导入、执行以下代码即可
1 package cc.cc.c; 2 3 import java.io.*; 4 import org.gjt.jclasslib.io.ClassFileWriter; 5 import org.gjt.jclasslib.structures.CPInfo; 6 import org.gjt.jclasslib.structures.ClassFile; 7 import org.gjt.jclasslib.structures.constants.ConstantUtf8Info; 8 9 public class Main { 10 public static void main(String[] args) throws Exception { 11 12 String filePath = "C:\\Main.class"; 13 FileInputStream fis = new FileInputStream(filePath); 14 DataInput di = new DataInputStream(fis); 15 ClassFile cf = new ClassFile(); 16 cf.read(di); 17 CPInfo[] infos = cf.getConstantPool(); 18 19 int count = infos.length; 20 for (int i = 0; i < count; i++) { 21 if (infos[i] != null) { 22 System.out.print(i); 23 System.out.print(" = "); 24 System.out.print(infos[i].getVerbose()); 25 System.out.print(" = "); 26 System.out.println(infos[i].getTagVerbose()); 27 if (i == 21) {//刚刚找到的是21位置 28 ConstantUtf8Info uInfo = (ConstantUtf8Info) infos[i]; //刚刚那里是CONSTANT_Utf-8_info所以这里要用这个 29 uInfo.setBytes("baidu".getBytes()); 30 infos[i] = uInfo; 31 } 32 } 33 } 34 //这种方式也可以,一样的 35 /* if(infos[count] != null) { 36 ConstantUtf8Info uInfo = (ConstantUtf8Info) infos[i]; //刚刚那里是CONSTANT_Utf-8_info所以这里要用这个 37 uInfo.setBytes("baidu".getBytes()); 38 infos[count] = uInfo; 39 }*/ 40 41 cf.setConstantPool(infos); 42 fis.close(); 43 File f = new File(filePath); 44 ClassFileWriter.writeToFile(f, cf); 45 } 46 }
本修改方式参考了https://blog.csdn.net/betterandroid/article/details/14520667