How to change methods in a .class file without recompiling

I need to modify an existing compiled .class file. In fact, I even have the sources of this, but I can’t just change and recompile it because of many dependencies that I don’t have.

Therefore, I need to change 2 methods. Both of them are of type void . The first contains only two lines, which are calls to other methods of the same class, i.e.

public void a() { System.out.println("a"); } public void b() { System.out.println("b"); } public void ca() { a(); b(); } 

And I need to change the ca sp method, which only calls the () method.

The second method I need to change contains some logic, but I want to clear it altogether, i.e. have an empty body method that does nothing.

How can i do this?

0
source share
9 answers

If you do not have the necessary dependencies, how are you going to use this code? I would highly recommend that you devote your time to compiling this normally, rather than just modifying the binary. It will probably be better in the long run.

+4
source

I would look at AspectJ and set triggers for each call ok. Then you can easily block this call and call instead.

+1
source

Try this question in Java Bytecode editors.

Java bytecode editor?

However, I think John Skeet's answer is the one that really applies here.

+1
source

I'm not sure you can change it in the first place, but even if you succeeded, I would not recommend this. A cleaner solution would be to extend your class and override the implementation of the ca() method to call only the a() method.

0
source

If method a is publicly available, the easiest way is to use an aspect ( Aspect-Oriented Programming , AspectJ ) and intercept every call to ca Instead of calling ca just call a .

0
source

Have you tried looking in thought? I have limited experience with it, but I'm not sure if you want to do this.

0
source

You can use Javaasist to modify an existing class file.

0
source

I had a similar problem.

I had to modify the method in a class file without a source. This method strongly crossed out exceptions, so I had to fine-tune it. I decompiled the class using the Classfile Analyzer (http://classfileanalyzer.javaseiten.de/) I edited the resulting file and recompiled it using the Jasmine assembler.

Using Apache BCEL, you can accomplish the same thing, but in a more elegant way - at runtime - not the way I described above at compile time.

0
source

You can use the java decompiler to open the class file and edit it and save.

Here is one good decomp -> http://java.decompiler.free.fr/

0
source

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


All Articles