覆盖java中的类 [英] Override class in java
问题描述
假设我有一个项目 K
K 取决于 lib.jar
在 lib.jar
中,有一个名为的类xyzFoo
如果我在 K中创建相同的类 xyzFoo
,然后在这个项目中,当我创建 Foo
的实例时,JVM现在将使用 Foo
strong> K 而不是 lib.jar
?
If i create the same class x.y.z.Foo
in K , then in this project when I create a instance of Foo
, now will JVM use Foo
in K rather than in lib.jar
?
如果它不稳定或取决于某些事情,如何确保 Foo
应该使用 K 的版本而不是 lib.jar
?
And if it's unstable or depends on something , how to make sure that Foo
should use K's version rather than lib.jar
?
推荐答案
独立应用程序中的Java类加载行为(至少没有自定义类加载器)是稳定的。确保你的k.jar(或路径)在 -cp
java arg
Java class loading behaviour in a standalone application (at least with no custom classloaders) is stable. Make sure that your k.jar (or path) comes before lib.jar in -cp
java arg
java -cp k.jar lib.jar ...
或将依赖项添加到K项目的/META-INF/MANIFEST.MF
or add dependencies to /META-INF/MANIFEST.MF of your K project as
...
Class-Path: lib1.jar lib2.jar
...
并运行
java -jar k.jar
k.jar类将首先加载
k.jar classes will be loaded first
在Maven中它是
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
...
这篇关于覆盖java中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!