Override class in java

為{幸葍}努か 提交于 2019-12-01 13:58:09

问题


Assume I have a project K

K depends lib.jar

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

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 ?


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


回答1:


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 ...

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

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

and run

java -jar k.jar

k.jar classes will be loaded first

in Maven it is

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


来源:https://stackoverflow.com/questions/14168314/override-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!