淺談兩個jar包中包含完全相同的包名和類名的加載問題
首先從表現(xiàn)層介紹,后續(xù)后深入原理。
1、先簡單介紹maven如何生成jar文件方便測試
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>Main.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
配置了一個manifest標簽來配置Main函數(shù)的入口。然后通過如下指令來實現(xiàn)打包。
mvn assembly:assembly
2、自定義兩個jar包,其中包含相同包名和類名
與export的導入順序有關(guān)。只會加載第一個,并且運行正常。
3、自定義jar和jdk包, 其中包含相同的包名和類名
與export的導入順序有關(guān)。同樣是只會加載第一個,但是如果加載自定義的jar運行會報錯。加載 jdk正常。
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
4、mvn jar包沖突常用命令
mvn dependency:analyze,mvn dependency:tree
以上這篇淺談兩個jar包中包含完全相同的包名和類名的加載問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java加載本地庫的方法之System.load與System.loadLibrary
最近在做的工作要用到本地方法,所以下面這篇文章主要介紹了Java加載本地庫的方法之System.load與System.loadLibrary的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-09-09

