Can I get the name of the jarfile with path from a class inside the jar?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Albert_Scherer
Posted On:   Tuesday, March 19, 2002 02:54 PM


Does anyone know how to get the name of a jar file (including the path) from a class inside the jar?


The class returns info from a jar's manifest. I'd like the class to read its own manifest without hardcoding the jar filename.

Re: Can I get the name of the jarfile with path from a class inside the jar?

Posted By:   Terry_Laurenzo  
Posted On:   Tuesday, March 19, 2002 03:41 PM

I'll reserve comment on whether obtaining the jar file name is the "right" way to do what you're after.


As far as I am aware, there is no standard way to find the jar filename. There are, however, at least two non-standard ways:


1. Analyze the java.lang.classpath system property. It contains a list of all user jars. You can step through each one, creating a URLClassLoader with it. You can then attempt to load your class through the new ClassLoader. When you get a hit, you've found your jar. There is one caveat. To avoid the delegation model for class loading, you must find the boot class loader for the JVM and use it as the parent to your newly created URLClassLoader. I have used the following algorithm before to accomplish this:

ClassLoader cl=MyClass.class.getClassLoader().getParent();
ClassLoader bootCl=null;
for (;;) {
// For all intents and purposes, the boot class loader is the first one that does not contain our class
try {
Class clazz=Class.forName(MyClass.class.getName(),false,cl);
} catch (Throwable t) {
bootCl=cl;
break;
}

cl=cl.getParent();
if (cl==null) break;
}


2. Analyze the url returned by Class.getResource(). You will need a resource in your jar to look for. Call URL url=MyClass.class.getResource("someresource.txt"); Then parse the result of url.toString(). If I recall, the syntax is something like:

jar:somepath/somefile.jar!com/company/someresource.txt

Of course, this is non-standard, too.


I seem to recall there being a way to read manifest entries through an API. It's been a while, though.

About | Sitemap | Contact