How to override a method in a jar file?
I have a method in a开发者_如何学C class and a jar file is created using this class. The jar file is included in the project.
How can I override this method in the application?
@Pablo Santa Cruz is right (+1): you cannot change existing code. You have to inherit existing class and override what you want in subclass.
BUT if you really want to change something in existing compiled module you can still do it using byte-code modification techniques. There are a lot of packages that can do this. A popular higher level package that implements aspect-oriented paradigm for Java AspectJ can also help.
You need to subclass the class inside your JAR and then override the method. There is no way to "change" an existing method on an existing class in Java unless you change the source code and recompile it.
If you mean to kind of 'patch' the current behavior, then you'll need to copy the existing java file, update the method you want to override and place its .class ahead in the CLASSPATH.
If you're talking about overriding the method in terms of inheriting from the class and then overriding it (i.e. from a polymorphic viewpoint) then unless the class is final you can extend from it as you would any other.
If you're talking about changing the method behaviour inside the jar file itself, you'll need to get the source, change the method yourself, then recompile it and repackage it in another jar file. Note however I really wouldn't recommend that approach especially if the jar is a common library jar - someone maintaining your code later on will be really confused / hacked off if the behaviour of a library class has been altered (bug fixes aside)!
If you haven't got the source then yes, you can hack the bytecode and do things that way. But I'm pretty confident that isn't what's needed here :-)
If you are thinking about overriding a method in an already loaded class then look at this Java reflection: How do I override or generate methods at runtime?
精彩评论