Discussion on loading two jar packages containing exactly the same package name and class name

  • 2020-10-07 18:42:31
  • OfStack

First, the presentation layer is introduced, followed by in-depth principles.

1. Briefly introduce how maven generates jar files for testing purposes


<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>
 Configure the 1 a manifest Tag to configure Main The entry of the function. The packaging is then implemented using the following instructions. 
 
mvn assembly:assembly

2. Customize two jar packages that contain the same package name and class name

Related to the import order of export. Only the first one will load, and it will work fine.

3. Custom jar and jdk packages, which contain the same package name and class name

Related to the import order of export. Again, only the first one will be loaded, but an error will be reported if the custom jar run is loaded. jdk loads normally.


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 packet conflict common commands

mvn dependency:analyze, mvn dependency:tree


Related articles: