1

I have an application deployed on Tomcat server. I used this stackoverflow link to find out the absolute path of the loaded class like below :

Code1:

  getClass().getClassLoader().getResource(".").getPath();

Code2:

  Thread.currentThread().getContextClassLoader().getResource(".").getPath();

Expected result:

  /D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/

Actual result:

  /D:/ProgramFiles/Tomcat-7.0.26/lib/

Was really confused with the result found. Finally I tried below:

Code1:

  getClass().getClassLoader().getResource("/").getPath();

Code2:

  Thread.currentThread().getContextClassLoader().getResource("/").getPath();

And I finally got my result:

  /D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/

So my question is as below:

a) Can you please explain why this happened ?

b) Also, please tell me if there is any other better way to get my expected result than what I used ?

Community
  • 1
  • 1
sunny_dev
  • 765
  • 3
  • 15
  • 34

1 Answers1

0

That's because getResource(".") returns the "current" folder where the calling class is. In your case the calling class is the classloader of your webapp which is declared in the tomcat lib, which should be located at tomcat/lib folder.

The getResource("/") returns the root folder of your classpath, which is pointing by the webapp classloader to WEB-INF/classes.

DiogoSantana
  • 2,404
  • 2
  • 19
  • 24
  • Can you give any reference to your last sentence? Also can you give a shot at answering my point b) at bottom of question – sunny_dev Sep 24 '14 at 12:24
  • The reference: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String). But that answer is a resume from my empiric knowledge. – DiogoSantana Sep 24 '14 at 15:54