如何覆盖jar文件中的方法?
我在一个类中有一个方法,并且使用该类创建了一个 jar 文件。 jar 文件包含在项目中。
如何在应用程序中重写此方法?
I have a method in a 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
@Pablo Santa Cruz 是对的(+1):您无法更改现有代码。您必须继承现有的类并覆盖子类中您想要的内容。
但是如果您确实想更改现有编译模块中的某些内容,您仍然可以使用字节码修改技术来完成。有很多包可以做到这一点。为 Java AspectJ 实现面向方面范例的流行的高级包也可以提供帮助。
@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.
您需要在 JAR 中对该类进行子类化,然后重写该方法。除非更改源代码并重新编译,否则无法“更改”Java 中现有类的现有方法。
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.
如果您打算“修补”当前的行为,那么您需要复制现有的 java 文件,更新要覆盖的方法并将其 .class 放在 CLASSPATH 中的前面。
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.
如果您正在谈论从类继承然后覆盖它(即从多态的角度)方面覆盖该方法,那么除非该类是最终类,否则您可以像任何其他类一样从它扩展。
如果您正在谈论更改 jar 文件本身内部的方法行为,则需要获取源代码,自己更改方法,然后重新编译它并将其重新打包到另一个 jar 文件中。但请注意,我真的不会推荐这种方法,特别是如果该 jar 是一个常见的库 jar - 如果库类的行为被改变(除了错误修复),稍后维护您的代码的人将会非常困惑/被砍掉!
如果您没有源代码,那么是的,您可以破解字节码并以这种方式执行操作。但我非常有信心这不是这里所需要的:-)
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 :-)
如果您正在考虑重写已加载的类中的方法,请查看此 Java 反射:如何在运行时重写或生成方法?
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?