java修改class⽂件
最近因为⼯作需要修改class⽂件中⼀个变量的值,特此记录
2、到要修改的变量所在的地址
3、创建⼀个java⼯程、并且将jclasslib.jar导⼊、执⾏以下代码即可
;
2
3import java.io.*;
4import org.gjt.jclasslib.io.ClassFileWriter;
5import org.gjt.jclasslib.structures.CPInfo;
6import org.gjt.jclasslib.structures.ClassFile;
7import org.gjt.stants.ConstantUtf8Info;
8
9public class Main {
10public 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
19int count = infos.length;
20for (int i = 0; i < count; i++) {
21if (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());
27if (i == 21) {//刚刚到的是21位置
28 ConstantUtf8Info uInfo = (ConstantUtf8Info) infos[i]; //刚刚那⾥是CONSTANT_Utf-8_info所以这⾥要⽤这个
29 uInfo.setBytes("baidu".getBytes());
java创建文件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 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论