java 覆盖java中的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14168314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:19:42  来源:igfitidea点击:

Override class in java

javaoverridingclassloader

提问by Hymanalope

Assume I have a project K

假设我有一个项目K

Kdepends lib.jar

K取决于lib.jar

In lib.jar, there is a class named x.y.z.Foo

在 中lib.jar,有一个名为的类x.y.z.Foo

If i create the same class x.y.z.Fooin K, then in this project when I create a instance of Foo, now will JVM use Fooin Krather than in lib.jar?

如果我x.y.z.FooK 中创建相同的类,那么在这个项目中当我创建一个实例时Foo,现在 JVM 将FooK 中使用而不是在lib.jar



And if it's unstable or depends on something , how to make sure that Fooshould use K's version rather than lib.jar?

如果它不稳定或依赖于某些东西,如何确保Foo应该使用K的版本而不是lib.jar

采纳答案by Evgeniy Dorofeev

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 -cpjava arg

独立应用程序中的 Java 类加载行为(至少没有自定义类加载器)是稳定的。确保您的 k.jar(或路径)在-cpjava arg 中的lib.jar 之前

java -cp k.jar lib.jar ...

or add dependencies to /META-INF/MANIFEST.MF of your K project as

或将依赖项添加到您的 K 项目的 /META-INF/MANIFEST.MF 作为

...
Class-Path: lib1.jar lib2.jar
...

and run

并运行

java -jar k.jar

k.jar classes will be loaded first

k.jar 类将首先加载

in Maven it is

在 Maven 中它是

<build>
    <plugins>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
         ...