File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Identify jar that a class is embedded into? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Identify jar that a class is embedded into?" Watch "Identify jar that a class is embedded into?" New topic
Author

Identify jar that a class is embedded into?

Dinesh Ramakrishnan
Greenhorn

Joined: Dec 04, 2006
Posts: 14
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

Joined: Mar 06, 2001
Posts: 13459

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

Joined: May 27, 2008
Posts: 225

Java classes are generally associated with a ProtectionDomain, which has a CodeSource, which has a location as a URL.

Try:

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

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()).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Identify jar that a class is embedded into?
 
Similar Threads
packing java file into JAr file
Doubt
New forum for Sun Certified Web Component Developer
How to make our own jar files and how to acess the methods in the jar
Consume authentication web services