前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java-查看JVM从哪个JAR包中加载指定类

Java-查看JVM从哪个JAR包中加载指定类

作者头像
小小工匠
发布2021-08-16 16:18:29
1.1K0
发布2021-08-16 16:18:29
举报
文章被收录于专栏:小工匠聊架构

背景

有的时候,我们经常会碰到java.lang.NoSuchMethodError的错误信息。 究其根源,是由于JVM的 全盘负责委托机制导致的。 关于 全盘负责委托机制 ,请查看另一篇博文 全盘负责委托机制

特别是对于一些web项目,jar包很多,如何精确的查找呢?


方式一

将下面的JSP文件,放到web容器的根路径下,启动web容器,通过 http://ip:port/projectname/srcAdd.jsp?className=XXXXXX

比如:

这里写图片描述
这里写图片描述

运行web项目,访问

代码语言:javascript
复制
http://localhost:8080/hello-spring4/srcAdd.jsp?className=org.springframework.beans.factory.annotation.Autowired
这里写图片描述
这里写图片描述

srcAdd.jsp

代码语言:javascript
复制
<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.security.*,java.net.*,java.io.*"%>
<%!
  public static URL getClassLocation(final Class cls) {
    if (cls == null)throw new IllegalArgumentException("null input: cls");
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    // java.lang.Class contract does not specify if 'pd' can ever be null;
    // it is not the case for Sun's implementations, but guard against null
    // just in case:
    if (pd != null) {
      final CodeSource cs = pd.getCodeSource();
      // 'cs' can be null depending on the classloader behavior:
      if (cs != null) result = cs.getLocation();
      if (result != null) {
        // Convert a code source location into a full class file location
        // for some common cases:
        if ("file".equals(result.getProtocol())) {
          try {
            if (result.toExternalForm().endsWith(".jar") ||
                result.toExternalForm().endsWith(".zip"))
              result = new URL("jar:".concat(result.toExternalForm())
                               .concat("!/").concat(clsAsResource));
            else if (new File(result.getFile()).isDirectory())
              result = new URL(result, clsAsResource);
          }
          catch (MalformedURLException ignore) {}
        }
      }
    }
    if (result == null) {
      // Try to find 'cls' definition as a resource; this is not
      // document.d to be legal, but Sun's implementations seem to         //allow this:
      final ClassLoader clsLoader = cls.getClassLoader();
      result = clsLoader != null ?
          clsLoader.getResource(clsAsResource) :
          ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
  }
%>
<html>
<head>
<title>srcAdd.jartitle>
head>
<body bgcolor="#ffffff">
  使用方法,className参数为类的全名,不需要.class后缀,如
  srcAdd.jsp?className=java.net.URL
<%
try
{
  String classLocation = null;
  String error = null;
  String className = request.getParameter("className");

  classLocation =  ""+getClassLocation(Class.forName(className));
  if (error == null) {
    out.print("类" + className + "实例的物理文件位于:");
    out.print("");
    out.print(classLocation);
  }
  else {
    out.print("类" + className + "没有对应的物理文件。");
    out.print("错误:" + error);
  }
}catch(Exception e)
{
  out.print("异常。"+e.getMessage());
}
%>
body>
html>

方式二

工具类 ClassLocationUtils.java

代码语言:javascript
复制
package com.xgj.master.ioc.classloaderUtil;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 * 

 * @ClassName: ClassLocationUtils

 * @Description: tools to find which jar does the class come from 

 * 
 */
public class ClassLocationUtils {

    /**
     * find the location of the class come from
     * @param cls
     * @return
     */
    public static String where(final Class cls) {
        if (cls == null)throw new IllegalArgumentException("null input: cls");
        URL result = null;
        final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
        final ProtectionDomain pd = cls.getProtectionDomain();
        if (pd != null) {
            final CodeSource cs = pd.getCodeSource();
            if (cs != null) result = cs.getLocation();
            if (result != null) {
                if ("file".equals(result.getProtocol())) {
                    try {
                        if (result.toExternalForm().endsWith(".jar") ||
                                result.toExternalForm().endsWith(".zip"))
                            result = new URL("jar:".concat(result.toExternalForm())
                                    .concat("!/").concat(clsAsResource));
                        else if (new File(result.getFile()).isDirectory())
                            result = new URL(result, clsAsResource);
                    }
                    catch (MalformedURLException ignore) {}
                }
            }
        }
        if (result == null) {
            final ClassLoader clsLoader = cls.getClassLoader();
            result = clsLoader != null ?
                    clsLoader.getResource(clsAsResource) :
                    ClassLoader.getSystemResource(clsAsResource);
        }
        System.out.println(result.toString());
        return result.toString();
    }

}

运行查找

代码语言:javascript
复制
package com.xgj.master.ioc.classloader;

import com.xgj.master.ioc.classloaderUtil.ClassLocationUtils;

public class ClassLoaderTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ClassLocationUtils.where(java.lang.Thread.class);
    }

}

运行结果:

这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/07/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 方式一
  • 方式二
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档