Java 如何找到部署在Tomcat中的类的绝对路径?

Java 如何找到部署在Tomcat中的类的绝对路径?,java,classpath,Java,Classpath,我在Tomcat服务器上部署了一个应用程序。我使用此stackoverflow查找加载类的绝对路径,如下所示: 代码1: getClass().getClassLoader().getResource(".").getPath(); getClass().getClassLoader().getResource("/").getPath(); 代码2: Thread.currentThread().getContextClassLoader().getResource(".").

我在Tomcat服务器上部署了一个应用程序。我使用此stackoverflow查找加载类的绝对路径,如下所示:

代码1:

  getClass().getClassLoader().getResource(".").getPath();
  getClass().getClassLoader().getResource("/").getPath();
代码2:

  Thread.currentThread().getContextClassLoader().getResource(".").getPath();
  Thread.currentThread().getContextClassLoader().getResource("/").getPath();
预期结果:

  /D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/
实际结果:

  /D:/ProgramFiles/Tomcat-7.0.26/lib/
我真的对发现的结果感到困惑。最后,我尝试了以下方法:

代码1:

  getClass().getClassLoader().getResource(".").getPath();
  getClass().getClassLoader().getResource("/").getPath();
代码2:

  Thread.currentThread().getContextClassLoader().getResource(".").getPath();
  Thread.currentThread().getContextClassLoader().getResource("/").getPath();
我终于得到了我的结果:

  /D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/
因此,我的问题如下:

a) 你能解释一下为什么会这样吗

b) 另外,请告诉我是否还有比我使用的更好的方法来获得预期结果?

这是因为getResource(“.”)返回调用类所在的“当前”文件夹。在您的例子中,调用类是webapp的类加载器,它在tomcat库中声明,应该位于tomcat/lib文件夹中


getResource(“/”)返回类路径的根文件夹,该文件夹由webapp类加载器指向WEB-INF/classes。

您能引用最后一句话吗?另外,你能试着回答我问题底部的b点吗?参考资料:。但这个答案是根据我的经验知识写的简历。