Reflectively loading classes from jar file

Hi,

I want to load and then instantiate all classes that lie under a secific package all compressed in a jar file. So, I have an app that uses example.jar :

example.jar - package structure

com

| example

| __ Foo.class

| __ Bar.class

| __ Example.class

| stuff

| __ Util.class

My code within the root app to load the classes from the jar is:

publicclass ReflectionHelper{

public ReflectionHelper(){

}

publicstatic Class getClassInstanceFromJar()throws Exception{

ClassLoader cl = Thread.currentThread().getContextClassLoader();

URL resource = cl.getResource("com/example");

System.out.println("Package: " + resource);

URLClassLoader ucl =new URLClassLoader(new URL[]{resource}, cl);

Class clazz = ucl.loadClass("com.example.Foo");

System.out.println("Loaded: " + clazz.getName());

return clazz;

}

publicstaticvoid main(String[] args)throws Exception{

ReflectionHelper.getClassInstanceFromJar();

}

}

Everything seem to work fine - the class is loaded normally. The question here is how can I get an Enumeraton or whatever of all resources/URLs that lie under this package so I can load them all without having to say specifically load Foo, load Bar and load Example?

Thanks,

akz

[2168 byte] By [ar.kaza] at [2007-11-27 10:27:18]
# 1

Hint: The genius of Gosling is that every class is in a file with the same

case sensitive name. ;)

To load plugins that are in a directory I just do a extension filtered

File.listFiles(). I dont know how this would work in a Jar file though.

Im sure there must be a programmatic way to get a list of jar

contents.

TuringPesta at 2007-7-28 17:44:42 > top of Java-index,Java Essentials,Java Programming...
# 2

bingo:

http://www.java-tips.org/blog/java-se/how-to-list-contents-of-a-jar-file-in-a-java-program.html

http://java.sun.com/j2se/1.4.2/docs/api/java/util/jar/package-summary.html

TuringPesta at 2007-7-28 17:44:42 > top of Java-index,Java Essentials,Java Programming...
# 3

Thanks for the links, I had already found these, but I was kinda hoping that I wouldn't have to go all through this.

As I get it, the class loader has already "opened" tha jar and read the class files and all other resources that may lie in there. Then why do I myself have to do programmatically something that has already been done ?

Am I getting something wrong here about class loaders? Isn't there another way?

ar.kaza at 2007-7-28 17:44:42 > top of Java-index,Java Essentials,Java Programming...