简体   繁体   中英

Read the class file and replace content of the class file

I am compiling this Java file and I get one class file. My task is to change the Static content "Hello" in the Class file and replace with "Hi". How to read the Class file first, and how to replace the static content?

public class test {

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

}

Is there any standard code(A template) for that ?

You need to use some Java bytecode instrumentation libraries like ASM. Good to start to read links are:

Does your solution need to be in Java? You can use Jawa to accomplish the same in Python with a lot less boilerplate than ASM and its equivalents.

Install it: pip install jawa

Then:

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)

Result:

$ java test
Hi

Full documentation is at http://jawa.tkte.ch . Regardless of what tool you end up using it's absolutely required to read the JVM ClassFile specification or you won't really understand what's going on. You can find it at https://docs.oracle.com/javase/specs/jvms/se10/html/jvms-4.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM