Find where java class is loaded from

前端 未结 11 1289
独厮守ぢ
独厮守ぢ 2020-11-22 06:22

Does anyone know how to programmaticly find out where the java classloader actually loads the class from?

I often work on large projects where the classpath gets v

11条回答
  •  遥遥无期
    2020-11-22 06:38

    Jon's version fails when the object's ClassLoader is registered as null which seems to imply that it was loaded by the Boot ClassLoader.

    This method deals with that issue:

    public static String whereFrom(Object o) {
      if ( o == null ) {
        return null;
      }
      Class c = o.getClass();
      ClassLoader loader = c.getClassLoader();
      if ( loader == null ) {
        // Try the bootstrap classloader - obtained from the ultimate parent of the System Class Loader.
        loader = ClassLoader.getSystemClassLoader();
        while ( loader != null && loader.getParent() != null ) {
          loader = loader.getParent();
        }
      }
      if (loader != null) {
        String name = c.getCanonicalName();
        URL resource = loader.getResource(name.replace(".", "/") + ".class");
        if ( resource != null ) {
          return resource.toString();
        }
      }
      return "Unknown";
    }
    

提交回复
热议问题