查找Java类来源jar包

 @Test

  public void getClassLocation() throws Exception {

    Class cls = DefaultListableBeanFactory.class;

    URL rt = null;

    final String clsResource = cls.getName().replace(".", "/").concat(".class");

    final ProtectionDomain pd = cls.getProtectionDomain();

    if (pd != null) {

      final CodeSource cs = pd.getCodeSource();

      if (cs != null) {

        rt = cs.getLocation();

      }

      if (rt != null) {

        if ("file".equals(rt.getProtocol())) {

          if (rt.toExternalForm().endsWith(".jar") || rt.toExternalForm().endsWith(".zip")) {

            rt = new URL("jar:".concat(rt.toExternalForm()).concat("!/").concat(clsResource));

          } else if ((new File(rt.getFile()).isDirectory())) {

            rt = new URL(rt, clsResource);

          }

        }

      }

    }

    if (rt == null) {

      final ClassLoader loader = cls.getClassLoader();

      rt = loader != null

          ? loader.getResource(clsResource)

          : ClassLoader.getSystemResource(clsResource);

    }

    System.err.println(rt);

  }

猜你喜欢

转载自ylsn1982.iteye.com/blog/2244482