How can I edit a class file and add code to a compiled Java class?
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 I edit a compiled .class file and add my own code?
There are several ways to edit class file:
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.
Disassemble .class to "assembly" (usually Jasmin syntax), modify it, assemble back. Krakatau is a good tool that should be able to do it.
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.
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