Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Identify jar that a class is embedded into?

 
Dinesh Ramakrishnan
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Might be a weird question..

Whilst executing a class, is it possible to identify its jar or its location (file system or URI)

I have an issue where I have a class in 2 different jar's and not sure which one is getting picked and executed by the classloaders.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Convert the fully qualified Class name into a file name (ending with .class) then use the ClassLoader to find the URL to that file. The URL is able to provide a reference to a location within the JAR, so you will get an answer in the form of <path-to-jar>:<path to file> or something like that.
 
Carey Evans
Ranch Hand
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java classes are generally associated with a ProtectionDomain, which has a CodeSource, which has a location as a URL.

Try:

 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David O'Meara:
Convert the fully qualified Class name into a file name (ending with .class) then use the ClassLoader to find the URL to that file. The URL is able to provide a reference to a location within the JAR, so you will get an answer in the form of <path-to-jar>:<path to file> or something like that.

Correct. Consider the following:

Output:
jar:file:/C:/Program%20Files/Java/jre1.6.0_05/lib/rt.jar!/java/lang/String.class

That is built as follows:
jar: - to indicate it is in a JAR file
file:/C:/Program%20Files/Java/jre1.6.0_05/lib/rt.jar - a URL to the JAR file itself
! - to indicate it is inside a JAR file
/java/lang/String.class - the file inside the JAR file

So if you cut off the jar: and everything after !, then you get a URL to the file. Convert it to a File using new File(url.toURI()).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic