Class.forname("").newInstance();   =   Problem!!  ;)

I am distributing the application I am developping as a Jar file...
In my application, there is a tool which interacts with a Database..
As there is more than 1 existing database, and that they all require different drivers, I do not want to have to put every driver into my jar file, since it makes the file too big... I'd like to make it possible to download the drivers separatly, as another jar file... Although when I do that, I am not able to create a new instance of the driver...
Here's what I have:
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
This works fine when the driver has been included in the same jar file as my program.. How could I get it to work if the driver is in a separate Jar file, in the same folder as the jar file of my own application?

I am distributing the application I am developping as
a Jar file...
In my application, there is a tool which interacts
with a Database..
As there is more than 1 existing database, and that
they all require different drivers, I do not want to
have to put every driver into my jar file, since it
makes the file too big... I'd like to make it
possible to download the drivers separatly, as another
jar file... Although when I do that, I am not able to
create a new instance of the driver...
Here's what I have:
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
This works fine when the driver has been included in
the same jar file as my program.. How could I get it
to work if the driver is in a separate Jar file, in
the same folder as the jar file of my own application?I think the problem may be the classpath since it has to include the jar name specifically to find the classes in them. Perhaps you can set a new classpath with the System.setProperties() function so that the Class.forName() will work. I haven't tried that so I don't know if it will work.

Similar Messages

  • Class.getConstructor().newInstance()  problem!!

    Hi all,
    I would like to dynamically create an object using the Class.getConstructor(). newInstance() methods. I store the constructors in a hashtable, and dynamically decide which constructor to call at runtime.
    But now I am facing a problem of casting my results. It always return a java.lang.Object, and I'll have to explicitly cast it into the desire class.
    Is there any way to avoid these static casting problems? I have the required class name passing dynmically, but now I cannot even compile due to the static casting error..
    thanx.

    Hello,
    The purpose of reflection is to be able to manipulate classes and objects dynamically. Therefore, logically (in the application that you have described ) you would be potentially dealing with different classes. However, it is recognized that you need to invoke some method. My suggestion would be to implement an interface (as you will potentially not know the class) or use the Method (of a particular signature and name) object to invoke it. Static casting goes against the grain of dynamic creation.
    Ironluca

  • Class.forName().newInstance(): InstantiationException for subclass

    I use classes not known at compile time. So far, these classes implemented an interface and I instantiated via
    final MyInterface fd = (MyInterface) clazz.newInstance();and this worked fine. Now, an interface is not enough anymore and those classes need to subclass a new superclass. For compatibility, I let my new super class also implement the old interface "MyInterface", but the code above doesn't work anymore as it throws a
    java.lang.InstantiationException: one.two.Julia$1
         at java.lang.Class.newInstance0(Class.java:340)
         at java.lang.Class.newInstance(Class.java:308)This looks like some inner class, but none of these classes have any inner classes - they are rather simple classes with no constructors and no other superclass/interface.
    I also tried to cast to the new superclass, but with no success. What could be the problem? (Inserting explicitaly an empty constructor didn't help either). Also tried deleting all classes; restart IDE/computer; ...
    If I simple switch back for the classes to only implement the interface, it works again.

    Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.
    1) Print out clazz.getClassName() right before calling newInstance.
    2) Post the code for whatever class getClassName() returns.

  • Can Class.forName("SomeClassName").newInstance() work in all classes?

    I saw some classes don't have a method called "newInstance()".
    but I have seen some advices say that is better using "Class.forName().newInstance()" than using "Class.forName()".

    I saw some classes don't have a method called
    "newInstance()".If you have class Foo, and you do Class.forName("Foo").newInstance();you're not calling Foo's newInstance method. You're calling java.lang.Class' newInstance method. You have a Class object that represents the Foo class. You tell that Class object newInstance() which invokes the public no-arg constructor of class Foo (as if you had done new Foo()). If Foo doesn't have a public no-arg constructor, you'll get an exception.
    but I have seen some advices say that is better using
    "Class.forName().newInstance()" than using
    "Class.forName()".They do two completely different things, and Class.forName().newInstance() first does Class.forName() and then class newInstance() on what that returns.
    Class.forName("Foo") returns the Class object that is associated with class Foo. It also loads the class if it hasn't already been loaded. It returns an instance of java.lang.class
    newInstance() calls the public, no-arg ctor of that class, if that ctor exists. Otherwise it throws an exeption. If it succeeds, it returns an instance of Foo.

  • Class.forName problem

    Hi,
    I'm using "Java Invocation API" to load a class and call a generic method of it,
    but the "forName" call fails with error:
         Exception in thread "Thread-4" java.lang.ClassNotFoundException: HelloWorld
              at java.lang.Class.forName0(Native Method)
              at java.lang.Class.forName(Class.java:217)
    here is my (pseudo) code:
    // connect to my class "HelloWorld"
    myClass = (*envP)->FindClass(env, "HelloWorld")
    // connect to class "Java/lang/Class"
    classClass = (*env)->FindClass(env, "java/lang/Class")
    // get the id of Class.forName method
    forNameID = (*env)->GetStaticMethodID(env, classClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;")
    // j name of HelloWorld
    jClassName = (*env)->NewStringUTF(env, "HelloWorld")
    // call forName -> fails
    jClassObject = (*env)->CallStaticObjectMethod(env, classClass, forNameID, jClassName)
         -----> Exception in thread "Thread-4" java.lang.ClassNotFoundException: HelloWorld
              at java.lang.Class.forName0(Native Method)
              at java.lang.Class.forName(Class.java:217)
    Sustem: MacOSX 10.2.8
    Java Version: 1.4.1
    $CLASSPATH env var: /System/Library/Frameworks/JavaVM.framework/Versions/1.4.1/Classes
    Can somebody help me or point me to some useful URL about this?
    Thanks

    Here is a simple app that demonstrates my problem. I compiled and ran it on MacOSX but I have the same problem on windows. Copy the following code in a file named "javatest.c", cd to that directory and compile it with commad:
    gcc -o javatest javatest.c -framework JavaVMthen run it with:
    ./javatestCode:
    #include <JavaVM/jni.h>
    //===========================================================================================
    static void print_exception(JNIEnv *envP)
         // output the exception
         if (envP && ((*envP)->ExceptionOccurred(envP) != NULL))
         {     (*envP)->ExceptionDescribe(envP);
              (*envP)->ExceptionClear(envP);
    //===========================================================================================
    int main()
    JavaVMInitArgs     vm_args;
    JavaVM               *jvm;
    JavaVMOption        options[5];
    char               *classPathEnv;
    char               *classPathString;
    jint               res;
    JNIEnv                *envP = NULL;
    jclass               jlcClass;
    jmethodID          forNameID;
    jstring               jClassName;
    jobject               jClassObject;
         vm_args.version = JNI_VERSION_1_2;
         // options
         vm_args.nOptions = 5;
         options[0].optionString = "-verbose:class" ;
         options[1].optionString = "-verbose:jni" ;
         options[2].optionString = "-verbose:gc" ;
         classPathEnv = (char *)getenv( "CLASSPATH" );
         if (!(classPathString = (char*)malloc(strlen( "-Djava.class.path=" ) + strlen(classPathEnv) + 1)))
    printf("malloc failed\n");
              exit(1);
         sprintf(classPathString, "%s%s" ,"-Djava.class.path=" , classPathEnv);
         options[3].optionString = classPathString;
         options[4].optionString = "vfprintf" ;
         options[4].extraInfo = vfprintf;
         vm_args.options = options;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Load the jvm
         res = JNI_CreateJavaVM(&jvm, (void**)&envP, &vm_args);
         if (res != JNI_OK)
         {     printf("CreateJavaVM failed\n");
              exit(1);
         // find the class "java/lang/Class"
         if (!(jlcClass = (*envP)->FindClass(envP, "java/lang/Class")))
         {     printf("FindClass java/lang/Class failed\n");
              print_exception(envP);
              exit(1);
         // find the method ID of Class.forName
         if (!(forNameID = (*envP)->GetStaticMethodID(envP, jlcClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;")))
         {     printf("GetStaticMethodID forName failed\n");
              print_exception(envP);
              exit(1);
         // make a java string of my "HelloWorld" class
         if (!(jClassName = (*envP)->NewStringUTF(envP, "HelloWorld")))
         {     printf("NewStringUTF failed\n");
              print_exception(envP);
              exit(1);
         // call method Class.forName
         if (!(jClassObject = (*envP)->CallStaticObjectMethod(envP, jlcClass, forNameID, jClassName)))
         {     printf("CallStaticObjectMethod of forName failed\n");
              print_exception(envP);
              exit(1);
         // fail with:
         // java.lang.ClassNotFoundException: HelloWorld
         //        at java.lang.Class.forName0(Native Method)
         //        at java.lang.Class.forName(Class.java:115)
    return 0;
    }HelloWorld java code (compiled in a .class file located in $CLASSPATH folder):
    public class HelloWorld
         public static void main (String args[]) throws Exception
              System.out.println ("HelloWorld");
    }Someone can help me about this?

  • Having trouble with Class.forName & Class.newInstance

    i have a string name of a JPanel class i want to place on a TabbedPane. the JPanel class is in another package, that i import.
    i have been trying all kinds of ways to do this, and it is not working. does anyone have any ideas on how to do this?
    i need: myTabPane.addTab("financial calc", new myBzPanel());
    i tried: myTabPane.addTab("financial calc", Class.newInstance(Class.forName("myBzPanel()"));
    without any success.
    any ideas appreciated. thanks.

    The Class.newInstance() method does not take any arguement and you passed a wrong stuff to the Class.forName(String) method.
    Class c = Class.forName("mypackage.myBzPanel");
    myBzPanel bz = (myBzPanel)c.newInstance();
    myTabPane.addTab("financial calc", bz);

  • Class.forName("com.proj.someclass").newInstance()

    This works fine if "someclass" is in classpath but doesn't work if "someclass" is in jar file. How to make it work with classes packed into jar?

    Hi Mike.
    I think you need to write your own customized ClassLoader. Haven't done it myself, but I know the question has been up before, and ansered, and problem solved... Do some search. And maybee you coud be more specific about what you want to achive. Is this an applet or an application? And why do you need to use Class.forName? And why do you want the class to be in a .jar file?
    Ragnvald Barth
    Software enigneer

  • Problems with Class.forName("com.sun.sql.jdbc.db2.DB2Driver")

    In sun java studio enterprise 8
    I'm able to connect to my local DB2 sample database by creating a database schema.
    But when I try to execute a java class (main) using
    Class.forName("com.sun.sql.jdbc.db2.DB2Driver"). It returns a not found condition.
    what am I doing wrong? do I have to point the classpath to some directory?

    try to add jar containing driver to
    Your project -> Properties -> Libraries -> Run list.

  • Class.forName() throws null exception in servlet

    Hi, just wondering if anyone having this similar problem:
    when i try to load a class using Class.forName() method inside a servlet, it throws null exception.
    1) The exception thrown is neither ClassNotFoundException nor any other Error, it's "null" exception.
    2) There's nothing wrong with the code, in fact, the same code has been testing in swing before, works perfectly.
    3) I have include all necessary jars/classes into the path, even if i haven't, it should throw ClassNotFoundException instead, not "null" exception.

    I have tried to detect any possible nullable variable, and it is able to run until line 15. The exception thrown is actually null only... not NullPointerException... which is why i have confused...
    the message i received is "PlugInException: null".
    The code is at follow:
    * Load plugin
    * @return ArrayList of plugins
    * @exception PlugInException PlugInException
    01 public ArrayList loadPlugin()
    02 throws PlugInException
    03 {
    04 PlugIn plugin;
    05 ArrayList plugins = new ArrayList();
    06
    07 for (int i = 0; i < configLoader.getPluginTotal(); i++)
    08 {
    09 try
    10 {
    11 if (debugger > 0)
    12 {
    13 System.out.print("Loading " configLoader.getPluginClass(i) "...");
    14 }
    15 if (Class.forName(configLoader.getPluginClass(i)) == null)
    16 {
    17 if (debugger > 0)
    18 {
    19 System.out.print(" not found");
    20 }
    21 }
    22 else
    23 {
    24 if (debugger > 0)
    25 {
    26 System.out.println(" done");
    27 }
    28 plugin = (PlugIn)(Class.forName(configLoader.getPluginClass(i)).newInstance());
    29 plugin.setContainer(container);
    30 plugins.add(plugin);
    31 }
    32 }
    33 catch (Exception e)
    34 {
    35 throw new PlugInException("PlugIn Exception: " + e.toString());
    36 }
    37 }
    38
    39 return plugins;
    40 }

  • Class.forName() ????

    Hello, I have the following problem:
    1. I create a class with "Class comp1 = Class.forName(strName);"
    2. With creating an instance custom the constructor some parameters.
    3. With "Constructor[ ] myconstr = comp1.getConstructors();" I get all Constructors.
    4. With "Class[ ] paramTypes = myconstr.getParameterTypes();" I get the parameter types
    question: Can I find somehow parameter name?
    Thanks for your help!!!
    Hallo, ich habe folgendes Problem:
    1. Ich erzeuge eine Klasse mit "Class comp1 = Class.forName(strName);"
    2. Beim Erzeugen einer Instanz brauch der Konstruktor einige Parametern.
    3. Mit "Constructor[] myconstr = comp1.getConstructors();" bekomme ich alle Konsturktoren.
    4. Mit "Class[] paramTypes = myconstr[i].getParameterTypes();" kann ich die Parametertypen bekommen
    Frage: Kann ich irgendwie Parametername rausfinden?
    Vielen Dank f�r die Hilfe!!!

    A method signature consists of the methods name and the parameter types. Nothing more is stored in the class-files. So there is no way to address a parameter by it's name in java.
    You may want to do something like:
    Class[] paramTypes=new Class[] { A.class, B.class };
    Constructor constructor=C.class.getConstructor(paramTypes);
    C cObj= (C) constructor.newInstance(new Object[] ( a, b));

  • Class.forName("AClassName") always yields in an exception

    Dear Experts
    I am trying to get a classname at runtime and Class c = Class.forName always returns an exception
    I will appreciate your help in this regard. Anyways the full code is as follows:
    interface MyInter
        void accept();
        void display();
    class IntegerSorter implements MyInter {
        public void accept()
            System.out.println("IntegerSorter....................");
        public void display()
            System.out.println("Displays IntegerSorter...........");
    class StringSorter implements MyInter {
        public void accept()
            System.out.println("StringSorter....................");
        public void display()
            System.out.println("Displays StringSorter.............");
    public class Main {
        public static void main(String[] args) {
            Class c=null;
            MyInter m=null;
            String s="IntegerSorter";
            try
                 c = Class.forName(s);
            } catch (Exception e1) {
                System.err.println(e1.getMessage());
            try {
                m = (MyInter) c.newInstance();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            m.accept();
            m.display();
    }Edited by: standman on Mar 18, 2011 1:41 PM

    standman wrote:
    I am trying to get a classname at runtime and Class c = Class.forName always returns an exceptionThat's not enough information; which Exception?
    Plus, I ran your exact code o my machine, and got absolutely no exception. Are you posting the exact code that demonstrates the problem?
    try
    c = Class.forName(s);
    } catch (Exception e1) {
    System.err.println(e1.getMessage());
    }As an aside, don't log exceptions like that. Although it looks fine on so small a code, it's way not enough information if you have to debug such a "trace" in a non-trivial program.
    Instead log the exception's stack trace ( e1.printStackTrace() ), or use a logging library (for bigger programs).
    Regards,
    J.

  • Trouble w/ multiple applets dynamically starting and Class.forName()

    I'm trying to start applets dynamically and I see strange behavior on some systems it works fine and gets the applet class from the jar file. On other systems it makes an http request back to the server to try and get the class. I don't know where in the Class or ClassLoader it's deciding whether to get this class from the jarfile or from the server and all of these classes are contained in the jarfile? Any suggestions?
    Here's the method to start new applets
    public Component startApplet( String className ) {
    System.out.println("Starting applet "+className);
    Class appletClass = null;
    JApplet japplet = null;
    try {
    appletClass = Class.forName("com.actsolar.ui.applet."+className);
    System.out.println(appletClass);
    japplet = (JApplet)appletClass.newInstance();
    japplet.init();
    } catch (Exception e) {
    System.out.println("startapplet Exception: "+e.getMessage());
    return japplet;
    thanks,
    andrew

    Hi,
    I have seen the same problem when I mix up small letters and BIG LETTERS.
    Ex :
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <applet code="Function3.class"width="100" height="100">
    </applet>
    </html>
    will work with Function3.class
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <applet code="function3.class"width="100" height="100">
    </applet>
    </html>
    Will NOT work.
    Maybe this will help you , I am also new on JAVA so maybe you make the same mistake like I did ?
    Best Regards,
    Didier.

  • Class.forName, how to use it in the case?

    we have a java application:
    c:\app\TestForName.class
    inside the app, there is a call:
    Class.forName("ClassLib");
    ClassLib.class is a simplest class for testing with no package.
    ClassLib.class can be in any directory except the app's directory
    c:\app
    because ClassLib.class stands for our library class for multiple projects and multiple uses, it is not allowed to be in a special app directory.
    and, ClassLoader and URLClassLoder are not suitable in our case.
    i tried following 3 ideas, none of them is OK, please help.
    1. put ClassLib.class in directory
    c:\lib\
    (that is c:\lib\ClassLib.class)
    call application with command -cp
    java -cp c:\lib;....; TestForName
    (method Class.forName("ClassLib") call is inside TestForName.class)
    2. put ClassLib.class in
    c:\jdk\bin\
    (VM says it is one of "java.library.path")
    java -cp ....; TestForName
    3. put ClassLib.class in
    c:\jdk\JAR\classes\
    (VM says if is one of "sun.boot.class.path")
    java -cp ....; TestForName
    i really wondering how to make Class.forName() call successfuf inside application TestForName.class
    1. which directory is right place for ClassLib.class
    2. how to change command line or java code inside TestForName.class
    thx for any help.

    Why don't u use a class loader. Try this code
    // loader class
    public class Loader  extends ClassLoader {
        String path;
        public Loader(String path) {
              this.path = path;
        public Class findClass(String name) {
            byte[] b = loadClassData(path+name+".class");
            return defineClass(name, b, 0, b.length);
        private byte[] loadClassData(String name) {
            File file = new File(name);
            byte[] data = null;
            try {
                InputStream in = new FileInputStream(file);
                data = new byte[ (int) file.length()];
                for (int i = 0; i < data.length; i++) {
                    data[i] = (byte) in.read();
            catch (IOException ex) {
            file = null;
            return data;
    // in your caller class use
       Loader loader = new Loader(libPath); // lib path may be taken from a command line arg
       Object main = loader.loadClass("ClassLib", true).newInstance();I think this is what u r looking for
    Uditha Nagahawatta

  • Class.forName() with dynamic String

    I'm trying to create objects of a class whose name depends on a runtime database lookup. So my code looks like this:
    package com.mycompany.ourproduct.ourpackage;
    String className = rs.getString(1);
    Class c = Class.forName(className);
    When I run the program, I get a ClassNotFoundException. But everything runs fine if I replace the code above with this:
    package com.mycompany.ourproduct.ourpackage;
    // String className = rs.getString(1);
    String className = "com.mycompany.ourproduct.ourpackage.oursubpackage.MyClass"
    Class c = Class.forName(className);
    The problem seems to be in the dynamic linking. Although the class I'm trying to load is in a different package, it is a public class (and I can load it with a static string). Neither does moving it to the same package fix the problem.
    I've noticed that if I supply a mis-named class with a static string, the exception reads:
    java.lang.ClassNotFoundException: com.mycompany.ourproduct.misspelledpackage.SomeClass
    but the same exception prints as follows when the string comes from the database:
    java.lang.ClassNotFoundException: com/mycompany/ourproduct/misspelledpackage/SomeClass
    I thought the difference was one of compile-time linking and run-time linking, but oddly enough, I still get the dots for misspelled classes that I (1) supply on the command line, (2) read from a file, or (3) concatenate from command line arguments plus info from a file. It's just when I pull the class name from the database that I get the slashes. Does anyone know what's going on?
    Here's what I get from java -version:
    java version "1.2.2"
    Solaris VM (build Solaris_JDK_1.2.2_05a, native threads, sunwjit)
    Any help would be greatly appreicated!

    Hmm. Weird. Have you looked at the String you're getting back from the database? Does it have slashes or dots? (Should be dots.) Have you made sure any leading/trailing spaces have been trimmed? Try doing classname.equals("com.mycompany... etc.") to see if it really is the same string as the constant that does work.
    If it turns out the String is correct, and the only difference is whether that String came from a databaes or a literal, then I don't know what's going on. The first step, though, is to verify whether that's really the case, or if you're not getting the String you think you are.

  • Question about Class.forName()

    I am trying to get an instance of a class by its name. Now, I have tried both creating it with the class's actual name and with the class's name including the package path and both times I got a java.lang.ClassNotFoundException: my/package/MyClass.
    I am reading the name out of a properties file and that's working just fine according to my logging information btu here is the code anyway:
    Properties prop = new Properties();
    try{
         java.io.FileInputStream in = new java.io.FileInputStream(inv.getPath());
         prop.load(in);
         String temp = prop.getProperty("myclass1");
         Class c = Class.forName(temp);
         rollen.put("user",c.newInstance());
         temp = prop.getProperty("myclass2");
         c = Class.forName(temp);
         rollen.put("admin",c.newInstance());
    }catch(Exception e){
         //I'm doing some more logging here, guess that's not very interesting
    }I deleted all the logging info from this code snippet to make it shorter. But I can tell you that the name does get read out as my.package.MyClass - and the package and class name are correct...
    The entries in the properties files look like this:
    myclass1=my.package.MyClass
    myclass2=my.package.MyOtherClass
    Can you help me fix this, please?

    Is your classpath okay? I tried this:
    pkg\MyClass.javapackage pkg;
    public class MyClass {
        public MyClass () {
            System.out.println ("Woohoo!");
    }Test.javapublic class Test {
        public static void main (String[] parameters) throws Exception {
            Class.forName ("pkg.MyClass").newInstance ();
    }This outputsWoohoo!as expected.
    Kind regards,
      Levi

Maybe you are looking for

  • How to change default fonts in Keynote?

    How to change default fonts in Keynote?

  • ST04問題

    目前ST04看到的情況如下: Data buffer Size              kb      2,097,152        Reads                 4,992,482,876 Quality            %           67.5          Physical reads        1,623,788,889                                                        writes  

  • I can't install Dreamweaver 8 on Windows 7

    Just like my title, I can't install Dreamweaver 8 on Windows 7 Release Candidate. I can start the installation, but it just stuck at "installing" for very long time,and the installation just can not Continue... I already try to running it in XP compa

  • CCM 2.0 Move column on list results

    Hi When in shop launch the catalogue (same window). Search and get a list of results The end column is ACTION with the shopping cart .gif for add to cart. Does anyone know how to move the column from the right hand side of the screen to the left. for

  • External HD not mounted on desktop but available in File Open

    I have an Intel MacMini which I have recently upgraded to Snow Leopard. The internal hard drive is about 80% full so I have bought a WD My Book Studio II 1TB external drive which I currently have attached by USB (as I saw some people were having issu