Why Class.forName?...

I'm trying to understand the use of Class.forName in JDBC programing. �What is the really goal for this class?
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(ClassNotFoundException ex){
// something
Regards.

I'm trying to understand the use of Class.forName in
JDBC programing. �What is the really goal for this
class?There are two implied questions...
-What does it do?
1. The class is loaded. All classes are loaded this way but normally the compiler does the work for you.
2. When a class is loaded, if there are any 'static initializers' in the class then those are run. Again true for any class when it is loaded.
3. JDBC drivers have a static initializer which registers the driver with the JDBC driver manager. See the DriverManager.registerDriver(Driver driver) method and the JDBC spec for more specific info.
-Why it is done this way?
As a guess because the original JDBC implementor(s) just found out about static initializers and thought they were 'cool'. It would be just as easy and more meaningful to do it using a different methodology.

Similar Messages

  • Why Class.forName is used to load the driver ?

    Hi all,
    Why Class.forName() is used to load the driver ?. Can I use any other method to load the driver safely ?.
    rgds
    Antony Paul

    That's still redundant. Sure, it works. Here are some equivalent forms:
        new MySqlDriver();
        DriverManager.registerDriver(new MySqlDriver());
        New LinkedList().add(new MySqlDriver());
        if (new MySqlDriver() == new MySqlDriver())
            System.out.println("department of redundancy department");
        Driver unusedVariable[] = new Driver[] { new MySqlDriver() };
        Class anotherUnusedVariable = MySqlDriver.class; // I'm not 100% sure this works
        new File(new MySqlDriver().toString());
        while (new MySqlDriver() == null)
        new Double(Math.sqrt(new MySqlDriver().toString().length()) / 42);

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

  • 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().

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

  • 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

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

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

  • Weblogic is getting shutdown by calling Class.forName("className")

    Hi,
    I have written the following code and it's running thru a web application in Weblogic. The problem is when calling Class.forName(), the weblogic server 9.2 gets shutdown.
    final static private String[] uib_cn = {
    "com.realm.portal.cda.ui.UIBuilder",
    "com.realm.rcash.rcoll.cda.ui.RCollUIBuilder",
    "com.realm.rcash.rpay.cda.ui.RPayUIBuilder"
    static {
    // Init the Constructor object for each UI builder class
    for (int i = 0; i <uib_cn.length; i++) {
    try {
    Class<?> c = Class.forName(uib_cn);
    uic[i] = c.getConstructor(IRbacParamsBean.class);
    } catch (Exception e) {
    log.error(e.getMessage(), e);
    The class containing this code in a jar file, is trying to load at runtime other class files which are in separate jar but all the jars are in same location WEB-INF/lib.
    Plz anyone can help me why this is happening and how to resolve this?
    Thanks & Regards
    Chanchal

    Is it due to an unhandled exception in the static initializer block? Are those classes available?

  • Class.forName() doesn't take dynamic class name

    String name="";
    String country="";
    String className = name + "_" + language + "_" + country;
    Class thisClass = Dynamicclassload.classLoad(className);
    System.out.println(className);
    Class class1 = Class.forName(className);
    child = (ResourceBundle) class1.newInstance();
    child.setParent( bundle );
    bundle = child;
    System.out.println("I am here");
    As i am passing classname as variable it throws an exception class not found exception.but if we write class name as the parameter of class.forName().it works.i am implementing in j2me
    why this happen? give me solution.

    The following classpackage test;
    public class TestLoad {
        String aString = "This is a Test";
        Integer anInteger = new Integer(42);
        public TestLoad() {
            System.out.println("aString = " + aString + ", anInteger = " + anInteger);
    }works correctly when loaded and instantiated by this class:package test;
    import java.util.logging.Logger;
    public class ExecuteTest {
        public static final Logger log = Logger.getAnonymousLogger();
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("test.TestLoad");
                TestLoad test = (TestLoad) clazz.newInstance();
            } catch (Exception ex) {
                log.severe(ex.toString());
    }and produces the string "aString = This is a Test, anInteger = 42"
    I used the following version of Java on Windows 2000
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)

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

  • For class.forName()

    Class.forName()
    method is used in DataBase Connection
    we cannot trap the returned value why n how it works in DataBase Connection

    Class.forName()
    method is used in DataBase Connection
    we cannot trap the returned value why n how it works
    in DataBase ConnectionYes, you can "trap" the returned value, but you don't need to. This call loads the driver class. For all JDBC drivers it is mandatory to have a static initializer that registers the driver at the DriverManager, so loading the class is all you need to do in order to make it known to JDBC.

  • Class.forName() debunked

    This issue is about: Dynamic loading and Inheritance.
    Debugging an odd ClassNotFoundException in a J2EE Application, I was involved investigating deeply Class.ForName(). This method - namely the version with only the class name as parameter - is used inside xsdbeans.jar, an optiopnal library, shipped with IBM WebSphere 5.x. Moving the jar from the EAR classloader to the server runtime classloader caused weird behavior on my app.
    I try to simplify the core question:
    Suppose class E extends B. Base class B declares an instance method, dynLoad(String name) that uses internally Class.forName(String name).
    Say 'e' an instance of E. Invoking e.dynLoad("Foo"), Class.forName("Foo") should use the ClassLoader of current class. But which is the 'current class': E or B? Is it the class of current object (E) or the declaring superclass (B)?
    My instinctive answer was: E. But my J2EE app was behaving as the current class was B. Indeed E and B may be defined by different classloaders, and this makes a big difference.
    A rapid lookup at Sun's docs confirmed my first hypothesis:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
    > Returns the Class object associated with the class or interface with the given string name.
    Invoking this method is equivalent to:
    Class.forName(className, true, currentLoader)
    where currentLoader denotes the defining class loader of the current class.
    ok, this is a little misleading, but going on:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String,%20boolean,%20java.lang.ClassLoader)
    > For example, in an instance method the expression:
    >
    Class.forName("Foo")
    is equivalent to:
    Class.forName("Foo", true, this.getClass().getClassLoader())
    Not equivocal. The current class is the class of current object, no matter (apparently) if the instance method is declared in a superclass.
    Right? Wrong. Here a minimal counter-example:
    //-- B.java
    import java.net.*;
    public class B {
        public void dynLoad(String name) throws Exception {
            System.out.println(getClass().getSuperclass()
                + " defining classloader is: "
                + getClass().getSuperclass().getClassLoader());
            System.out.println(getClass()
                + " defining classloader is: "
                + getClass().getClassLoader());
            System.out.println("\n1) Class.forName(\""+name+"\");");
            // Loading with 'currentLoader'
            Class.forName(name)
                .newInstance();
            System.out.println("\n2) Class.forName(\""+name
                +"\", true, this.getClass().getClassLoader());");
            // This should be equivalent (by Sun J2SE API spec)
            Class.forName(name, true, this.getClass().getClassLoader())
                .newInstance();
        public static void main(String[] args) {
            ClassLoader syscl = ClassLoader.getSystemClassLoader();
            if (!URLClassLoader.class.isInstance(syscl)) {
                System.err.println("Cannot continue the trick.");
                System.exit(1);
            URL[] urls = ((URLClassLoader)syscl).getURLs();
            // Yet Another ClassLoader
            URLClassLoader yacl = new URLClassLoader(urls) {
                // Force Parent-last delegation policy to assure
                // demanded classes are defined by _this_ classloader
                public Class loadClass(String name)
                    throws ClassNotFoundException {
                    Class c = findLoadedClass(name);
                    if (c == null) {
                        try {
                            // Simulate no visibility to base class to assure
                            // it is _not_ defined by this classloader too
                            if (name.equalsIgnoreCase("B")) {
                                throw new ClassNotFoundException();
                            c = findClass(name);
                        } catch (ClassNotFoundException e) {
                            c = getParent().loadClass(name);
                    return c;
            try {
                // Loading class E with a different classloader
                Class c = yacl.loadClass("E");
                c.getMethod("dynLoad", new Class[]{String.class})
                    .invoke(c.newInstance(), new Object[]{"Foo"});
            } catch (Exception ex) {
                ex.printStackTrace();
                System.exit(1);
    //-- E.java
    public class E extends B {
    //-- Foo.java
    public class Foo {
      public Foo() {
        System.out.println(getClass()
          + " defining classloader is: "
          + getClass().getClassLoader());
    }Running above B.main() produce the following output on Sun JDK 1.3, 1.4.2, 1.5:
    > class B defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
    class E defining classloader is: B$1@3d2c0480
    1) Class.forName("Foo");
    class Foo defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
    2) Class.forName("Foo", true, this.getClass().getClassLoader());
    class Foo defining classloader is: B$1@3d2c0480
    The evidence is that classloader used is not the same. in the case 1) it uses the classloader of superclass B. Hence the two form of Class.forName() invocation are not equivalent, as stated in Sun documentation.
    Disclosure
    The evidence is confirmed and explained looking at Sun's implementation of java.lang.Class.java and java.lang.ClassLoader.java: finally the Class.forName(String name) relies on sun.reflect.Reflection.getCallerClass(int) to find the famous 'current class' mentioned in the javadocs. This undocumented method returns the i-th caller class of current stack frames; each stack frame represents a method invocation coupled with its declaring class.
    I wonder why in Sun docs this poorly explained issue was remaining immutable from 1.3 to date. Furthermore: which was the intended behavior? Another reason to the long said "Class.forName() is evil..." or am I missing something?
    regards, Lorenzo

    Of course, it comes down to the question: What is the current class?
    Not something well defined. You are looking for this.getClass(), it's taking the class at compile time. If it went your way, woundn't that create an inconsistency in forName in static vs instance contexts?
    Actually I think the static approach is more natural, because it means that forName behaves the way that resolving external references work. Your way would also go against the spirit of Java security policies which requires references down the classloader chain something to be treated with suspision.
    The mechanism intended, I think, for these situations is the contextClassLoader property of Thread. When executing plugin type code the contextClassLoader should be set to the ClassLoader that loaded the plugin, and any references to resources or dynamic class loads from the plugin should be made using the contextClassLoader. This enables your shared library code to access classes and resources on behalf of the plugin code with access to classes and resources inside the plugin.
    Thus, if you write library code or other container stuff likely to be called from a plugin you should probably always use:
    Class cls = Thread.currentThread().getContextClassLoader().loadClass("foo");

Maybe you are looking for