1 year ago
#281782
tribbloid
In Java classgraph, How to find all jars loaded by Java classloader in runtime?
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?
java
jvm
classpath
classloader
classgraph
0 Answers
Your Answer