Replacing a method in a compiled .class file

An interesting question here. So I have the .jar I received and it is messy, which means that when I decompile the .class files, it is not 100% displayed, so I cannot recompile it. However, the only method I need to change has been completely converted (but the class does not work)). Is there a way to somehow change the .java code and implement the method replacement inside the class file without completely recompiling?

If this fails, then you are going to bytecode.

Thanks!

EDIT: As a follow-up question / or hack around replacing the WHOLE method. I'm just trying to change the variable that the method generates locally. If there are any better ways to do this.

+5
source share
3 answers

Depending on what you really want to do, I do not recommend decompiling / modifying / recompiling the code (whether legal, official, understandable, reasonable).

Using bytecode may not be the best solution, but if you want to follow this path, look at the ASM project , this is a widespread bytecode manipulation scheme used by many well-known projects.

If I were you, I would first try aspects ( AspectJ .) The strength of the aspects is that you do not touch the existing code, but tell the virtual machine what to do when / before / after / instead of calling a specific method. This allows you to specify the exact context and change, improve the behavior of the code by writing your own code separately.

Hope this helps.

+2
source

Sorry, this is not an answer, but it is too long for comment ...

I reflect on this code without using it as a library. Therefore, I really do not need to β€œuse” this code (otherwise I just mirror and call functions at runtime).

I would call the "reflection and call at run time" functions as code.

There may be reasons for this, but I would prefer to just call the function as a library function if possible (which should be possible if you can do the same using reflection).

... and manually reload it.

Nothing is simpler than extending a class and overriding the "wrong" method. As far as I know, even if you want to β€œenter” a method, you must have the code somewhere. How will you test such code? It would be much simpler just to extend the class ... Can you specify in more detail what you want to achieve by reasoning why you cannot use what I wrote above?

0
source

If you want to change only one method, you can actually extend class, and then the @Override method! I don't know if this is suitable for this, but it works!

0
source

Source: https://habr.com/ru/post/1238502/


All Articles