问题
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.
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?
回答1:
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.
回答2:
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.
回答3:
Try this question on Java Bytecode editors.
java bytecode editor?
However, I think Jon Skeet's answer is the one that really applies here.
回答4:
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.
回答5:
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
.
回答6:
Have you tried looking into reflection? I have limited experience with it, but I'm not sure what you want to do it possible.
回答7:
You can use Javaasist library to modify existing class file.
回答8:
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.
回答9:
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/
来源:https://stackoverflow.com/questions/5191888/how-to-change-methods-in-class-file-without-recompiling