最近遇到了一個問題,一份很老的代碼要修改裏面的變量,源碼早就和開發者一塊兒不翼而飛,其中引用了一些jar包致使沒法直接編譯,只能直接修改.class文件java
標準方式安裝插件ide
這裏咱們寫一個簡單的java方法idea
/** * @Description: * @author: wei.wang * @since: 2020/9/5 11:18 * @history: 1.2020/9/5 created by wei.wang */ public class HelloWorld { public static void main(String[] args) { String word = "Hello World"; System.out.println(word); } }
打開要修改的.class文件,點擊view->Show Bytecode With Jclasslib ,在Constants Pool中使用Text filter功能找到要修改的內容,咱們發現有一個String類型常量,指向23,點擊23就能看到要修改的內容spa
23是要修改的內容插件
/** * @Description: * @author: wei.wang * @since: 2020/9/4 19:42 * @history: 1.2020/9/4 created by wei.wang */ import java.io.*; import org.gjt.jclasslib.io.ClassFileWriter; import org.gjt.jclasslib.structures.CPInfo; import org.gjt.jclasslib.structures.ClassFile; import org.gjt.jclasslib.structures.constants.ConstantUtf8Info; public class Test { public static void main(String[] args) throws Exception { String filePath = "F:\\GitCode\\zero\\test111\\target\\classes\\HelloWorld.class"; FileInputStream fis = new FileInputStream(filePath); DataInput di = new DataInputStream(fis); ClassFile cf = new ClassFile(); cf.read(di); CPInfo[] infos = cf.getConstantPool(); int count = infos.length; System.out.println(count); for (int i = 0; i < count; i++) { if (infos[i] != null) { System.out.print(i); System.out.print(" = "); System.out.print(infos[i].getVerbose()); System.out.print(" = "); System.out.println(infos[i].getTagVerbose()); //對23進行修改 if(i == 23){ ConstantUtf8Info uInfo = (ConstantUtf8Info)infos[i]; uInfo.setBytes("Hello World HELLO WORLD".getBytes()); infos[i]=uInfo; } } } cf.setConstantPool(infos); fis.close(); File f = new File(filePath); ClassFileWriter.writeToFile(f, cf); } }
能夠看到已經修改完成code
public class HelloWorld { public HelloWorld() { } public static void main(String[] args) { String word = "Hello World HELLO WORLD"; System.out.println(word); } }