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

Similar Messages

  • 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

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

  • 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);

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

  • 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

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

  • 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

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

  • Dynamically instantiating objects using string name

    Hello to all.
    This is probably an easy question, but I am wondering how I can dynamically create instances of an object in a loop using a string variable as the name.
    The idea here is this:
                   while (someBooleanVariable) {
                        int count = 1;
    String objectName = "myObject" + count;
                        myObject objectName = new myObject; // How do I pass the objectName String variable as a name?
                        count++;
                   } // End while
    Of course this doesn't work - incompatible types, but the idea is that the code would create "myObject1," "myObject2," "myObject3," "myObject4," etc as long as someBooleanVariable = true using the objectName String variable.
    I am new to this and appreciate any help and ideas.
    Thanks!

    BigDaddyLoveHandles wrote:
    There's been this outbreak of people wanting to dynamically name their variables -- is this some sort of scripting disease?It's always been around. Shoot, I remember suffering from it when I first started out, because it seems so, hm I dunno, necessary at the time. Eventually the newbie (me) realizes that the variable "name" means nothing, that reference is everything.
    ... and then I discovered maps, and names were useful again. :o)

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

  • How can create the object ? Via class.forName

    Hi,
    i want to create the object via class.forname?........
    i have tryed like this Class obj=Class.forName("sample.Employee");
    but it gives error like this......
    java.lang.InstantiationException: sample.Employee
         at java.lang.Class.newInstance0(Class.java:291)
         at java.lang.Class.newInstance(Class.java:259)
         at sample.ArrayListTest.main(ArrayListTest.java:22)

    The line
    Class obj=Class.forName("sample.Employee");does NOT create a new object of class
    sample.Employee. It only loads the class and creates
    the Class object. You have to call newInstance() to
    create a new instance of the class:
    Object obj =
    Class.forName("sample.Employee").newInstance();I guess you already did something like that, because
    forName() itself doesn't throw an
    InstantiationException.
    For this to work, class sample.Employee must be in
    the classpath and it must have a public constructor
    that takes no arguments.this is my full code it dosn't work i don,t know
    public class ArrayListTest {
    public ArrayListTest() {  }
    public static void main(String[] args) {
    ArrayList employees = new ArrayList();
    // create some employees
    /* Employee employee_1 = new Employee("John", 2000);
    Employee employee_2 = new Employee("Carl", 3000);
    Employee employee_3 = new Employee("Ron", 4000);*/
    /*instead of this Employee employee_1 i want to create the new obeject by using*/
    try{
    Object obj = Class.forName("sample.Employee").newInstance();
    catch(Exception e)
    e.printStackTrace();
    // add them to your list
    //employees.add(employee_1);
    //employees.add(employee_2);
    //employees.add(employee_3);
    // display only the names your list
    for(int j = 0; j < employees.size(); j++) {
    Employee temp = (Employee)employees.get(j);
    System.out.println("nr. "+(j+1)+": "+temp.getName()+"\nnr. "+(j+1)+": "+temp.getSalary());
    // invoke the toString()-method from Employee
    for(int j = 0; j < employees.size(); j++) {
    Employee temp = (Employee)employees.get(j);
    System.out.println(temp.toString());
    } // class ArrayListTest
    again the same error occur................

  • Query on Class.forName() method

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

    You can do one of them at runtime.
    For example:
    public static void main(String[] args) {
       String className = args[0];
       Object o = Class.forName(className).newInstance();
    }It's essentially a part of the reflection API which is generally used when you don't know exactly what you want to manipulate at compile time.

  • 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

  • Class.forName() & Singleton

    I have a servlet which has a list item containing a list of all the object Singleton of my application.
    After select one of these, I would like to release this object.
    So, the value of the differents items is the name of the Singleton class.
    I use Class.forName() but this method try to execute the constructor and in a Singleton the constructor is private.
    So I would like to find a method to call the method getInstance() of my Singleton class and after instanciation of this class, I would like to call the method release().
    Have you got a solution for me...
    Thx

    Hi,
    Just a quick thought...
    You could use a Map to "map" the name from your list to the instance of the
    singleton and call your method that way (you would have to cast though, lots of "ifs"), or map it to the Method of the singleton class so you could use reflection to invoke it.
    There (to my knowledge) isn't a way to create an interface with static methods so casting or
    reflection seem the only way to call your release() method "dynamically"
    hope this helps

Maybe you are looking for

  • Can I use a photo as the color for my text swatches

    I want to create a set of letters (Lake in Wood Camping Resort) that use a photo of the campground as their swatch, instead of a solid color.  Can I do this?  If yes, how?  I am a novice at INDESIGN so need all the help I can get. My thought would be

  • Amp fried my video port!?

    Hello, I did something really dumb, and the consequence appears to be a bit weird: I plugged my guitar amp's headphone jack into my Macbook Pro's audio-in jack. I had read online that most people were saying it was safe and a couple said not to. I gu

  • Has anyone every had a green screen on their ipad?

    I just went to put on my Ipad and the screen is tinted green all over it! Just wondering if anyone has ever had this before?

  • User alv layout in standerd

    i want to hide some coulumns in standerd tcode, like qe51n , can i change it for only perticular user??? if yes then how?

  • What has happened to the 1520??

    Hi, erico64. The device screen is made of glass. This glass can be broken if the device drops on a hard surface or receives a substantial impact. The warranty of the it was voided due to physical damage. Since the device has the insurance with the pr