0

In the following question:

How to find which jars and in what order are loaded by a classloader?

It is stated that jars can only be listed for a URLClassloader, which for Java 8 and lower versions is the type of the context classloader. In Java 9+ such hypothesis no longer holds.

So I start looking into 3rd party libraries to figure out the universal way of doing it reliably. Unfortunately, I didn't find any reference of getURL() method in classgraph. The closest reference is in the utility library of scala 2.13:

   @tailrec
    def isAbstractFileClassLoader(clazz: Class[_]): Boolean = {
      if (clazz == null) return false
      if (clazz == classOf[AbstractFileClassLoader]) return true
      isAbstractFileClassLoader(clazz.getSuperclass)
    }
    def inferClasspath(cl: ClassLoader): String = cl match {
      case cl: java.net.URLClassLoader if cl.getURLs != null =>
        (cl.getURLs mkString ",")
      case cl if cl != null && isAbstractFileClassLoader(cl.getClass) =>
        cl.asInstanceOf[{val root: scala.reflect.io.AbstractFile}].root.canonicalPath
      case null =>
        val loadBootCp = (flavor: String) => scala.util.Properties.propOrNone(flavor + ".boot.class.path")
        loadBootCp("sun") orElse loadBootCp("java") getOrElse "<unknown>"
      case _ =>
        "<unknown>"
    }
    cl match {
      case null => s"primordial classloader with boot classpath [${inferClasspath(cl)}]"
      case _    => s"$cl of type ${cl.getClass} with classpath [${inferClasspath(cl)}] and parent being ${show(cl.getParent)}"
    }
  }

Unfortunately this is an internal function subjected to change in the future, it cannot be used as is.

So my question is: What's the reliable way of getting jars in runtime classpath that is future-proof?

tribbloid
  • 4,026
  • 14
  • 64
  • 103
  • I’m not sure what you mean by future-proof. A jlink’d modular application won’t have .jar files. A number of Java EE servers don’t use .jar files to form their classpaths, but rather a custom ClassLoader with a custom URL scheme. In the end, you simply cannot rely on the assumption that classes are loaded from .jar files. – VGR Mar 12 '22 at 04:41
  • 1
    Even the old `URLClassloader` does not require its URLs to point to jar files, most notably, there can be directories of the default filesystem. As VGR mentioned, now there can be module images. So what’s the point of this fixation on jar files? And the relevance of the “context classloader” in a tenacious myth. If you want a future proof solution, you have to describe the actual problem first. Whatever problem you want to solve by finding jar files first can be surely solved without. – Holger Mar 14 '22 at 09:09

0 Answers0