A self-modifying bytecode demo using the ASM library. The program computes a trigonometric expression, then rewrites its own .class file with an equivalent implementation — so the next run executes different bytecode.
- Java 25+
- Maven 3.6+
mvn clean package
java -jar target/java-asm-example-1.0-SNAPSHOT.jar 1.0 2.0Run it again to see the rewritten bytecode in action:
java -jar target/java-asm-example-1.0-SNAPSHOT.jar 1.0 2.0Entry point. Computes 2*sin((x+y)/2)*cos((x-y)/2) with the original calculation() method, then uses ASM to read its own compiled class file and rewrite the calculation method's bytecode with a different (but mathematically equivalent) implementation. The rewritten class is saved back to target/classes/SinusCalculation.class.
A ClassVisitor that intercepts the calculation method and randomly replaces its bytecode with one of two equivalent trigonometric forms:
sin(x) + sin(y)2*sin((x+y)/2)*cos((x-y)/2)