Why use Class.forName() ?

Why is it always adviced to use Class.forName( nameOfTheDriver ). Why dont we simply import the driver via the import statement ?
Please note that this topic is part of a bigger topic I published in Java programming about difficulties I had importing driver. See:
http://forums.java.sun.com/thread.jsp?forum=31&thread=147534
for more details.

Because using an import statement only tells the compiler about the driver. Class.forName() actually loads the driver when the program runs, which is what you want to happen.

Similar Messages

  • Why can't i use class.forName(str) ?

    Heys all i have this piece of code which is working fine:
    *try {*
    java.lang.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    *} catch (java.lang.ClassNotFoundException e) {*
    now the problem is that i was under the impression that i could use class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); but it wouldn't compile. does anyone know why is this so?

    Class.forName() says "call the static method forName() that is defined in java.lang.Class". It returns a reference to an instance of java.lang.Class.
    SomeClass.class is known as a class literal. It is not a member, not a field, not a method. It evaluates to a reference to an instance of java.lang.Class.
    You cannot do class.something().
    Edited by: jverd on Oct 26, 2010 9:46 AM

  • How to create an object of our own class by using Class.forName()??

    how to create an object of our own class by using Class.forName()??
    plzz anser my qustion soon..

    Class.forName does not create an object. It returns a reference to the Class object that describes the metadata for the class in question--what methods and fields it has, etc.
    To create an object--regardless of whether it's your class or some other class--you could call newInstance on the Class object returned from Class.forName, BUT only if that class has a no-arg constructor that you want to call.
    Class<MyClass> clazz = Class.forName("com.mycompany.MyClass");
    MyClass mine = clazz.newInstance();If you want to use a constructor that takes parameters, you'll have to use java.lang.reflect.Constructor.
    Google for java reflection tutorial for more details.
    BUT reflection is often abused, and often employe when not needed. Why is it that you think you need this?

  • ClassNotFoundException when using Class.forName(), thx

    in a study app, i try to use Class.forName() to load any class then get its properties (fields, methods etc. vs reflect).
    the (Frame based) app is in directory:
    c:\app\StudyApp.class
    there is a "Open class" button on the app, click the button, i use FileChooser to open any class file.
    i.e. open a class (assume it is not packaged)
    d:\dir\TheClass.class
    coding in StudyApp.java is:
    Class cls=Class.forName("TheClass");
    now a ClassNotFoundException throws when call Class.forName() above.
    it is easy to understand why throw the exception because i never tell where the class is. it is in directory
    d:\dir
    my question is: how to tell VM the directory.
    the directory d:\dir can not be applied to -classpath when run java.exe StudyApp, because the directory is random one at run-time.
    i tried to change System property (i.e. "java.class.path", 'user.dir" etc. none of them can fix the problem.
    thanks in advance for any help

    This probably does a lot more than you need:
    import java.util.*;
    import java.io.*;
    import java.util.jar.*;
    import java.lang.*;
    public class ClassFileFinder extends ClassLoader
         List cpath = new LinkedList();
         void addFile(File f) {
              if(f.isDirectory() || (f.isFile() && f.canRead() &&
                                          f.getName().endsWith(".jar")))
                   cpath.add(f);
         public byte[] classData(String className)  {
              String cname = className.replace('.', File.separatorChar) + ".class";
              Iterator it = cpath.iterator();
              while(it.hasNext()) {
                   File f = (File)it.next();
                   try {
                        if(f.isDirectory()) {
                             File cFile = new File(f, cname);
                             if(cFile.isFile()) {
                                  byte[] buf = new byte[(int)cFile.length()];
                                  InputStream in = new FileInputStream(cFile);
                                  int off  = 0, l;
                                  while((l = in.read(buf, off, buf.length - off)) > 0) {
                                       off += l;
                                       if(off >= buf.length) break;
                                  in.read(buf);
                                  in.close();
                                  return buf;
                        } else if (f.isFile()) {
                             JarFile jar = new JarFile(f);
                             JarEntry ent = jar.getJarEntry(cname);
                             if(ent != null) {
                                  byte[] buf = new byte[(int)ent.getSize()];
                                  int off = 0, l;
                                  InputStream in = jar.getInputStream(ent);
                                  while((l = in.read(buf, off, buf.length - off)) > 0) {
                                       off += l;
                                       if(off >= buf.length) break;
                                  in.close();
                                  return buf;
                   } catch (IOException e) {
              return null;          
         public Class findClass(String className) throws ClassNotFoundException{
              byte[] data = classData(className);
              if(data == null)
                   return getParent().loadClass(className);
              else
                   return defineClass(className,data,0, data.length);
    }Create an instance, Add directories and/or jar files with addFile then loadClass the class you want.

  • How to use class.forName

    I am trying to use Class.forName() from a string which is passed to me as argument.
    Class batchClass = Class.forName(args[1]);
    A jar file contains the class file for the string received above and I have this jar file in the manifest of my executable jar.
    I get a class not found exception when I run my executable jar
    Can some body give pointers..what could possibly be the issue.
    The jar file is in my classpath
    run script
    #!/bin/csh
    java -jar -DDBPROVIDER=NO -DDBUS_ROOT=$DBUS_ROOT -DVTNAME=$VTNAME ./jar/IntraDayDepotPositionBatch.jar MagellanStart IntraDayDepotPositionBatch INPUTFILE LOGFILE
    Exception
    Magellan program starting - program class IntraDayDepotPositionBatch
    Cannot find program class - IntraDayDepotPositionBatch
    IntraDayDepotPositionBatch
    java.lang.ClassNotFoundException: IntraDayDepotPositionBatch
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at com.db.mmrepo.app.IntraDayDepotPositionBatch.MagellanStart.main(Unknown Source)
    Thanks for your time and feedback on this

    actually i tried both...with package name and without package name..
    nothing worked...
    my manifest file also contains the path to the package..so does the classpath

  • Database connectivity without using Class.forName()

    Hi,
    Can anyone please tell how we can connect to a database without in java without using the Class.forName() method , and then how the database driver gets loaded.
    Regards,
    Tanmoy

    Hi,
    I recently wrote code that connects to a database without using Class.forName() in order to be compatible with Microsoft's JVM. I read about it here:
    http://www.idssoftware.com/faq-e.html#E1
    Basically, you create a new Driver object and use its connect method.
    Here's what my particular code ended up being:
    String url = "jdbc:mysql://localhost:3306/test?user=root&password=mypass";
    Driver drv = new org.gjt.mm.mysql.Driver();
    Connection con = drv.connect(url,null);

  • Instantiating object using Class.forName()

    What is the difference between instantiating using Class.forName() method and instantiating using the new operator?

    The difference is that you can use the new operator to instantiate an object, but you can't do it using Class.forName().
    But seriously folks...
    Presumably you're talking about Class.newInstance()--which often appears right on the heels of Class.forName().
    New gives you compile-time checks you don't get with Class.forName(). If it compiles with new, then you know the constructor in question exists on the class in question.
    With Class.newInstance() (and it's cousin (also called newInstance, I think) in the Constructor class), you can't be sure until you actually execute it whether that constructor even exists.
    New requires you to know the class at compile time. NewInstance lets you defer the specific class until runtime.
    New is simpler and more direct.
    (Did I just do your homwork for you? Hope not.)

  • Why is Class.forName( ) so useful?

    I still don't get why Class.forName so useful to java?
    If I do:
    Class c = Class.forName("dog");
    Dog d = c.newInstance();But what's wrong with:
    Dog d = new Dog();Why does java need that Class.forName thing? Can anyone give an counter example to demonstrate the case in my second way won't work?
    Thanks.

    cpthk wrote:
    I still don't get why Class.forName so useful to java?
    If I do:
    Class c = Class.forName("dog");
    Dog d = c.newInstance();But what's wrong with:
    Dog d = new Dog();Why does java need that Class.forName thing? Can anyone give an counter example to demonstrate the case in my second way won't work?
    System.out.println("Class to instantiate?");
    String className = scanner.nextLine();
    Class c = Class.forName(className);
    Object o = c.newInstance();Also, Class has a lot more methods besides just forName().

  • Need Help Loading Sqlbase Driver Using Class.forName(...

    I'm having trouble connecting to a Sqlbase database on my PC. The problem seems to be with loading the driver with the "Class.forName" method. My source code (listed below) is in the "C:\My Documents\java" folder. I installed the Sqlbase driver in "C:\com\centurasoft\java\sqlbase" folder. The driver installation modified my autoexec.bat file to include the line "SET CLASSPATH=C:\com\centurasoft\java\sqlbase".
    The epdmo database is in a folder on my D:\ drive.
    It seems to find the SqlbaseDriver.class file, but for some reason it can't load it. I would greatly appreciate any suggestions as to how I can fix this.
    With the line -- Class.forName("centura.java.sqlbase.SqlbaseDriver");
    The SqlbaseEx.java program will compile, but I get the following error
    when I try to run it:
    Exception in thread "main" java.lang.NoClassDefFoundError: SqlbaseDriver (wrong name: com/centurasoft/java/sqlbase/SqlbaseDriver)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    ... [several more lines like these]
    at SqlbaseEx.main(SqlbaseEx.java:25)
    With the line -- DriverManager.registerDriver(new SqlbaseDriver());
    The SqlbaseEx.java program will NOT compile. I get the following error:
    SqlbaseEx.java:21: cannot access SqlbaseDriver
    bad class file: C:\com\centurasoft\java\sqlbase\SqlbaseDriver.class
    class file contains wrong class: com.centurasoft.java.sqlbase.SqlbaseDriver
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    Also, does the line -- String url = "jdbc:sqlbase:epdmo";
    look OK? I've seen numerous examples and they all have some values separated by slashes //. Am I
    missing something here that will bite me when I get past this driver loading error?
    import java.sql.*;
    // Create the ...
    public class SqlbaseEx {
    public static void main(String args[]) {
    String url = "jdbc:sqlbase:epdmo";
    Connection con;
    String createString;
    createString = "create table COFFEES " +
    "(COF_NAME varchar(32), " +
    "SUP_ID int, " +
    "PRICE float, " +
    "SALES int, " +
    "TOTAL int)";
    Statement stmt;
    try {
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    // DriverManager.registerDriver(new SqlbaseDriver());
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
    try {
    con = DriverManager.getConnection(url, "SYSADM", "SYSADM");
    stmt = con.createStatement();
    stmt.executeUpdate(createString);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());

    Thanks for the reply.
    Upon further testing, I think my original post was slightly incorrect: if I use either of the following lines --
    Class.forName("com.centurasoft.java.sqlbase.SqlbaseDriver");
    or
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    I get the following error at runtime:
    ClassNotFoundException: com.centurasoft.java.sqlbase.SqlbaseDriver
    or
    ClassNotFoundException: centura.java.sqlbase.SqlbaseDriver
    It is when I use the line -- Class.forName("SqlbaseDriver");
    that I get the long error message in my original post.
    I don't understand why it can't find/load the driver. I feel like I've covered all the bases -- I've tried numerous variations of the driver name in the Class.forName method, my classpath variable seems to be set correctly. Does it matter what folder I compile my program in? Right now, I've just been compiling it in the same folder as the driver file -- c:\com\centurasoft\java\sqlbase.

  • Creating Object using Class.forName vs new

    Hello,
    Is there any difference between:
    Class c = Class.forName("Foo");
    Foo foo = (Foo) c.newInstance();
    and
    Foo foo = new Foo();
    Thanks.

    Simple search brings this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=614699

  • Why class.forName to load driver

    hi all,
    as most of the times the loading of jdbc driver is carried out
    by using the function class.forName, Why so ?
    as i tryied with creating the object of the driver class like
    Object driver = new <JDBC DRIVER>;and the code worked fine
    so is there any difference in the two methods of loading the
    drivers ?
    if not wot is the use of method class.forname ?
    thanx

    That 's fine, but what if you change database back end in near future.
    I will define a property and used class.forName ("read property").
    In your case, you have to change the code about loading the JDBC driver as well.
    Using std. JDBC API functionality and loading driver dynamically, leaves some of the part of the code that are not a candidate for a change in case back-end DB is changed.
    BS

  • Why Class.forName("driver class") ?

    Hi,
    whay we are using Class.forName("driver class"). why we dont import the driver package and access the required classes and methods?
    for eg:
    insead of calling
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); ,can we use import com.microsoft.jdbc.sqlserver.*; ?
    what is the use of DriverManager in this context? any connection between DriverManager and Class.forName() ?
    expecting answers.

    sure you can import the packages and use the classes directly but that defeats the whole purpose of pluggable drivers.
    Class.forName causes the class to be loaded and as stated before that should cause the driver to register itself with the driver manager.
    so then if you have a system where you are talking to several different database vendors then you don't have to worry about which is which as the DriverManager handles it for you.
    the big pros that i have actually seen though for having this be pluggable and not hard-coded (with the exception of the URL although you can do this dynamically as well) is what happens if you switch databases. if you import the package and use fully named classes and you switch databases at some point (could be just an upgrade of the same vendor's database) you are screwed.
    same problem could happen if you switch drivers for some reason.
    at any rate if you use things properly and are careful then you should only ever have to change your URL the rest of the code is fine if you use the DriverManager and use the drivers dynamically otherwise...

  • Strange use of Class.forName() in JDBC

    The following is the classical code to retreive data from a database via JDBC
            Connection con;
            Statement stmt;
            String querystring;
            String parametervalue = "";
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
            try {
                con = DriverManager.getConnection(dburl);
                stmt = con.createStatement();
                querystring = "select ParameterValue from Profile ";
                ResultSet rs = stmt.executeQuery(querystring);
                if(rs.next()) parametervalue = rs.getString("ParameterValue");
                rs.close();
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("-----SQLException-----");
                System.err.println("SQLState:  " + ex.getSQLState());
                System.err.println("Message:  " + ex.getMessage());
                System.err.println("Vendor:  " + ex.getErrorCode());
            return parametervalue;         but the use of Class.forName("com.mysql.jdbc.Driver") is strange. it doesn't need to get the returned Class
    like: Class t = Class.forName("com.mysql.jdbc.Driver"),and the DriverManager knows which driver to use!
    Any one can give an explanation?
    thanks

    * It's more natural from an OO perspective for me to
    tell the manager about the classes it manages thanfor
    the classes to know about the manager and tell it
    about themselves.
    No.Hmmm. Care to elaborate? I don't have anything to really back this up, but it seems to me that a class shouldn't have to know too much about the context in which it is used. Drivers shouldn't have to know that there is a DriverManager that will be managing them. IMHO.
    I thought of another reason: Since you're doing either the Class.forName or the DriverManger.register in the client, no work is saved there either way (as you said, register is just as easy to call as forName), but using Class.forName adds extra complexity in the Drivers. I guess this is probably the same as, or very close to "protected users from themselves" though.
    If the forName() doesn't happen somewhere then the
    class doesn't get loaded.I'm thinking more along the lines of classes getting loaded in a different area of the code than the DB client. Some kind of plugin-type thing maybe, where the plugin manager automatically loads all the classes in a certain classpath-like set of diretories and jars, without knowing or caring what each one is (DB plugin, graphics plugin, encryption plugin, messaging plugin, etc.) or how it's used. The DB client then wouldn't know which specific driver(s) it has available, only that whatever was visible to the plugin manager will be loaded, and some subset of that could be DB drivers.
    In this situation, it's not appropriate for the plugin manager to register the drivers, since it doesn't know anything about JDBC, and it's not appropriate for the DB client to register them, since it doesn't know what classes the plugin manager loaded.
    I suppose the DB client could query the plugin manager for all its loaded plugins, then check if each one implements Driver, and if it does, then register it. Or maybe the plugin manager could even store a map whose keys are interface Class objects or interface names and whose values are lists of the plugins that implement that interface.
    I don't know if this scenario is used, or is even good design, but it doesn't seem too farfetched. This is the kind of situation where it seems to me the driver is the one in the best position to know both a) he has been loaded and b) he needs to be registered.

  • 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 }

  • What is Class.forName

    We are using Class.forName("driver class") statement for registering the driver class. But after writing this statement we are not using any refernce to that Class.forName, why it is needed actually.

    It causes the class to get loaded. That in turn causes the static initializer to run. Which registers it as an available driver, allowing you to use it from within JDBC.

Maybe you are looking for

  • How to exit the execution in middle of a function module

    Hi Fox, I have a function which sometime needs more than 10 minutes to deliver a result. This is not acceptable thus this function will be given a time-out value in a second format after which the function should be stopped or killed. Do you have an

  • N00b question about the ABS

    Hey, I am new to Arch and I'm about to install it on my machine (used it a bit in a virtual machine) and I have a small nooby question about the ABS. According to the wiki: https://wiki.archlinux.org/index.php/Arch_Build_System "Running abs as root c

  • Configuration error message....

    Greetings! Recently purchased a refurbished 17" MacBook Pro - complete with 2.16GHz Intel Core Duo. Got all settled in, loaded up Final Cut Pro 4.0, clicked it and got the following message: "Configuration error: This software requires certain hardwa

  • Skype Will Not Sign In/Connect.

    I am unable to sign into skype. When I try to, it just sits in the Signing In screen for 5-10 minutes and then tells me Skype was unable to connect. I have tried several different suggestions from articles I have read. Wether it be cleaning out the r

  • Mail to groups in address book

    On previous Macs I was able to click on the address button in the New Message window and then click on the Group name in the address book and click on the "to" button and all the addresses in this group would show up in the address block of the messa