I have java code that is compiled to a .class file. There is a function that gets few parameters and do some action (e.g. get int x and int y and do x+y)

I want to add to this .class file code that checks if x=1 and call to another function(e.g. call to x-y and don't do x+y)

How can edit a compiled .class file and add my own code?

  • I edited the question, hopefully this is what you actually wanted to ask; if not, please clarify in a comment or edit it yourself. – Igor Skochinsky Feb 9 '18 at 16:19

There are several ways to achieve this:

  1. Decompile .class to .java source (not necessarily original source, but equivalent), make your changes, compile again. There are many Java decompilers out there, I won't list them all.

  2. Disassemble .class to "assembly" (usually Jasmin syntax), modify it, assemble back. Krakatau is a good tool that should be able to do it.

  3. Use a tool that can modify/patch the bytecode directly in the .class file. I haven't tried it, but Recaf claims to be able to do it.

  4. Hook the Java runtime interpreter to catch the moment it starts executing the target function and make it execute something else instead. This is somewhat implementation-specific but here's one example I know about which uses Java debugging protocol (JWDP): https://github.com/CrowdStrike/pyspresso

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.