开发者

How to change methods in .class file without recompiling

I need to change existing compiled .class file. Actually I have even sources of it, but I cannot just change and recompile it because of many dependencies that I don't have.

So I need to change 2 methods. Both them have void return type. The first contains just 2 lines that are calls of another methods of the same class, i.e.

开发者_如何学C
public void a() {
    System.out.println("a");
}

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

public void ca() {
    a();
    b();

}

And I need to change method ca sp that it calls only a() method.

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

How can I do this?


If you don't have the required dependencies, how are you expecting to use this code? I would strongly recommend that you devote your time to being able to compile this normally, instead of trying to just change the binary. It's likely to be a better bet in the long run.


I would take a look at AspectJ and set triggers to every call of ca. Then you can easily block that call and call a instead.


Try this question on Java Bytecode editors.

java bytecode editor?

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


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


If method a is public then the easiest way is to use an aspect (Aspect Oriented Programming, AspectJ) and intercept every call to ca. Instead of invoking ca just invoke a.


Have you tried looking into reflection? I have limited experience with it, but I'm not sure what you want to do it possible.


You can use Javaasist library to modify existing class file.


I had a similar problem.

I had to modify a method in a class file with no source. The method was rethrowing the exceptions badly so I had to tweak it. I have decompiled the class with Classfile Analyzer (http://classfileanalyzer.javaseiten.de/) I have edited then the resulted file and recompiled it with Jasmine assembler.

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


You can use a java decompiler for opening the class file and edit it and save it.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜