Java如何修改.class文件变量
最近遇到了一个问题,一份很老的代码要修改里面的变量,源码早就和开发者一起不知去向,其中引用了一些jar包导致无法直接编译,只能直接修改.class文件
idea安装jclasslib-bytecode-viewer插件
标准方式安装插件

准备要修改的.class文件
这里我们写一个简单的java方法
/**
* @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就能看到要修改的内容


修改.class文件中的变量
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);
}
}
执行结果
可以看到已经修改完成
public class HelloWorld {
public HelloWorld() {
}
public static void main(String[] args) {
String word = "Hello World HELLO WORLD";
System.out.println(word);
}
}
以上就是Java如何修改.class文件变量的详细内容,更多关于Java修改文件变量的资料请关注脚本之家其它相关文章!
相关文章
MybatisPlus的MetaObjectHandler与@TableLogic使用
这篇文章主要介绍了MybatisPlus的MetaObjectHandler与@TableLogic使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-04-04
springboot如何接收复杂参数(同时接收JSON与文件)
文章介绍了在Spring Boot中同时处理JSON和文件上传时使用`@RequestPart`注解的方法,`@RequestPart`可以接收多种格式的参数,包括JSON和文件,并且可以作为`multipart/form-data`格式中的key2025-02-02
Spring中@ControllerAdvice注解的用法解析
这篇文章主要介绍了Spring中@ControllerAdvice注解的用法解析,顾名思义,@ControllerAdvice就是@Controller 的增强版,@ControllerAdvice主要用来处理全局数据,一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder使用,需要的朋友可以参考下2023-10-10
JAVA对list集合进行排序Collections.sort()
这篇文章主要介绍了JAVA对list集合进行排序Collections.sort(),需要的朋友可以参考下2017-01-01
解决Spring运行时报错:Consider defining a bean o
该文章主要讲述了在使用Spring框架时,如果遇到某个bean未找到的错误,应该在配置文件中定义该bean,解决方法是在对应的类上添加@Component注解2025-01-01
springboot使用Mybatis-plus分页插件的案例详解
这篇文章主要介绍了springboot使用Mybatis-plus分页插件的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-05-05


最新评论