k9b
k9b

Reputation: 1493

Replacing a method in a compiled .class file

Interesting question here. So I have a .jar I received and it is obfuscated, meaning when I decompile the .class files it doesnt show up 100% perfect so I cannot recompile it. However the only method I need to change has been converted perfectly (but the class does not)). Is there a way to somehow change the .java code and inject replace the method within the class file without totally recompiling?

If this fails im going to bytecode.

Thanks!

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

Upvotes: 6

Views: 1893

Answers (3)

Grigoris Dimopoulos
Grigoris Dimopoulos

Reputation: 124

If you want to change just one method you can actually extend the class and then @Override the method! Don't know if this is the perfect way to do it,but it works!

Upvotes: 0

Betlista
Betlista

Reputation: 10549

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

I am reflecting this code, not using it as a library. So I dont really need to "use" this code (aka I'm just reflecting and calling functions at runtime).

I'd call the "reflecting and calling functions at runtime" as using the code.

There might be the reasons why to do that, but I'd prefer to simply call the function as a library function if possible (which should be possible if you can do the same using reflection).

...and manually overload it.

There is nothing simpler that extending the class and override a "wrong" method. As of my understanding even if you want to "inject" the method, you have to have the code somewhere. How you will test such code? It'd be a lot easier to just extend the class... Can you specify in bigger detail what you want to achieve with a reasoning why you cannot use what I wrote above?

Upvotes: 0

Kraal
Kraal

Reputation: 2877

Depending on what you really want to do, I do not recommand to decompile / modify / recompile the code (be it for legal, maintainance, understandability, testability reasons.)

Bytecode manipulation may not be the best solution either, but if you want to follow this way have a look at the ASM project, it's a widespread bytecode manipulation framework used by many known projects.

If I were you I would first give a try to aspects (AspectJ.) The power of aspects is that you don't touch existing code, but tell the VM what to do when / before / after / in place of calling a specific method. It allows you to point out the exact context and change, enhance the behavior of the code, by writing your own code in a decoupled fashion.

Hope it helps.

Upvotes: 2

Related Questions