当前位置: 移动技术网 > IT编程>开发语言>Java > 浅谈两个jar包中包含完全相同的包名和类名的加载问题

浅谈两个jar包中包含完全相同的包名和类名的加载问题

2019年07月19日  | 移动技术网IT编程  | 我要评论

首先从表现层介绍,后续后深入原理。

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函数的入口。然后通过如下指令来实现打包。
 
mvn assembly:assembly

2、自定义两个jar包,其中包含相同包名和类名

与export的导入顺序有关。只会加载第一个,并且运行正常。

3、自定义jar和jdk包, 其中包含相同的包名和类名

与export的导入顺序有关。同样是只会加载第一个,但是如果加载自定义的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包中包含完全相同的包名和类名的加载问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网