How to load class from JAR file

Hello, I want to load a class from a JAR file. It is saved under [b]/mnt/datadisk/java/share[/b], but altough I add it to library path the program fails loading class. here is code I use:
[code]
System.setProperty("java.library.path",System.getProperty("java.library.path")+":"+"/mnt/datadisk/java/share");
System.out.println(System.getProperty("java.library.path"));
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ) {
System.out.println("Class not found");
}
[/code]
Thanks for any advices

Comments

  • : Hello, I want to load a class from a JAR file. It is saved under [b]/mnt/datadisk/java/share[/b], but altough I add it to library path the program fails loading class. here is code I use:
    [code]
    System.setProperty("java.library.path",
    System.getProperty("java.library.path")+":"+"/mnt/datadisk/java/share");
    [/code]

    Changing this String has no effect (as you have found). Same goes for all the properties stored here (user directory etc).

    If you want to load classes dynamically, try [b]java.net.URLClassLoader[/b]. Either construct a [b]file://[/b] type url or use the [b]File.toUrl()[/b] method. Use the [b]loadClass[/b] method to get the [b]java.lang.Class[/b] and then use its [b]newInstance[/b] method to instantiate it. You can use [b]java.lang.reflect.Constructor[/b]s if they take arguments.

    This method of instantiation is only suitable if the type is in the main classpath (otherwise you'll still get class not found exceptions). But it'll work for JDBC drivers + the like.

    ---------------------------------
    [size=1](Its just my sig)
    HOWTO ask questions: http://catb.org/~esr/faqs/smart-questions.html[/size]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion