views:

101

answers:

2

Hi all,
I have an application which is extendable through java classes that conform to a given interface. If I run the program from the command line classes, I am able to instantiate the add-on classes using:

Class.forName("myAddon").newInstance();

However if I jar the application (setting the main class correctly), I get a class not found exception. Can anybody shed some light on what's going on here?

TIA, Adam

A: 

The class you're looking for isn't on the classpath. If its in a directory

i.e. MyClass.class MyJar.jar

You need to do:

java -classpath . -jar MyJar.jar

But really we need more info to answer the question. What is the main class set to in the jar manifest? What's your classpath? How do you specify which class to load?

Rob Spieldenner
Hi Rob,I thought that the classpath flag was ignored on the command line when -jar was specified. WRT your questions, the classpath is only the default classpath - no addiitonal parameters are set. The main class defined in the manifest is com.mycompany.Main, whihc is working correctly as the error is being thrown within the main method of the class.The class to be loaded is specified as a command line parameter. Adam
Adam
You either need to specify the classpath you need in the JAR's manifest or just invoke the class with java -cp whatever com.mycompany.Main
matt b
Is the class to be loaded on the default classpath?
Rob Spieldenner
+1  A: 

I have managed to get this working using a URLClassLoader, specifying the search path to be the current directory as follows:

URLClassLoader cl = new URLClassLoader(new URL[] {new File(".").toURI().toURL()});

Thanks for all your help,

Adam

Adam
Could you not put the class file in a jar? (Btw: `URLClassLoader.newInstance` is slightly better.)
Tom Hawtin - tackline
Good point- thanks.
Adam