读取类文件并替换类文件的内容

时间:2018-05-21 09:31:28

标签: java bytecode java-bytecode-asm

我正在编译这个Java文件,我得到一个类文件。 我的任务是更改类文件中的静态内容“Hello”,并替换为“Hi”。 如何首先阅读Class文件,以及如何替换静态内容?

public class test {

 public static void main(String[] args) {
     System.out.println("Hello");
 }

}

是否有任何标准代码(A模板)?

2 个答案:

答案 0 :(得分:1)

您需要使用一些Java字节码检测库,如ASM。很高兴开始阅读链接:

答案 1 :(得分:0)

您的解决方案是否需要使用Java?您可以使用Jawa在Python中完成相同的操作,并且比ASM及其等价物少得多。

安装它:from jawa.constants import String from jawa.classloader import ClassLoader # Create a ClassLoader for the current directory # and load your "test" class. test = ClassLoader('.')['test'] # Find the first String with the value "Hello" # in the constant pool. constant = test.constants.find_one( type_=String, f=lambda c: c.string.value == 'Hello' ) # Change it to your new value constant.string.value = 'Hi' # ... and save the new class. with open('test.class', 'wb') as new_test: test.save(new_test)

然后:

$ java test
Hi

结果:

Select count(empno), grade
from emp 
JOIN salgrade
  ON emp.SAL BETWEEN  salgrade.LOSAL AND   salgrade.HISAL
group by grade
order by grade;

完整文档位于http://jawa.tkte.ch。无论您最终使用什么工具,都必须阅读JVM ClassFile规范,否则您将无法真正理解正在发生的事情。您可以在https://docs.oracle.com/javase/specs/jvms/se10/html/jvms-4.html找到它。