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

Similar Messages

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

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

  • User-defined object problem,why can't I use?

    as follows:
    UObject.java
    package test1;
    public class UObject
    private String num;
    public UObject()
    public void setNum(String num)
    this.num=num;     
    public String getNum()
    return num;     
    Test.java
    package test1;
    public class Test
    public static void main(String args[])
    UObject U=new UObject();
    U.setNum("Squall");
    System.out.println(U.getNum());
    UObject[] U=new UObject[5];
    for(int i=0;i<U.length;i++)
    U.setNum(String.valueOf(i));     
    for(int i=0;i<U.length;i++)
    System.out.println(U[i].getNum());
    error:
    java.lang.NullPointerException
    why can't I use?please tell me why?thanks.
    ps:in Test.java's comments can run./**/.

    Please use code formatting tags in future! http://forum.java.sun.com/features.jsp#Formatting
    It would be easy to find the problem yourself if you printed out a stack trace e.g.
    public static void main(String args[])
    try
    UObject U=new UObject();
    U.setNum("Squall");
    System.out.println(U.getNum());
    UObject[] U=new UObject[5];
    for(int i=0;i<U.length;i++)
    U.setNum(String.valueOf(i)); 
    for(int i=0;i<U.length;i++)
    System.out.println(U.getNum());
    catch( Exception e )
    e.printStackTrace()
    }Tho code doesnt look lke it compiles to me!

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

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

  • Hi, my MacBook Air is not working anymore if it's not connected with the power cable. It's pretty new so I can't imagine that the battery is dead already. Why can't I use my MacBook Air without the power cable even though I charged it for hours?

    Hi, my MacBook Air is not working anymore if it's not connected with the power cable. It's pretty new so I can't imagine that the battery is dead already. Why can't I use my MacBook Air without the power cable even though I charged it for hours?

    Please take the Mac to  Apple store to have it checked out.
    Genius Bar reservation
    http://www.apple.com/retail/geniusbar/
    Best.

  • Why can't I use my mid 2010 macbook pro with 8GB memoir and NVIDIA GEForce GT 330M 256MB to run 3D in photoshop CC?

    Why can't I use my mid 2010 macbook pro with 8GB memoir and NVIDIA GEForce GT 330M 256MB to run 3D in photoshop CC?

    3-D is very memory intensive.
    System requirements | Photoshop
    Mac OS
    Multicore Intel processor with 64-bit support
    Mac OS X v10.7, v10.8, or v10.9
    2 GB of RAM (8 GB recommended)
    3.2 GB of available hard-disk space for installation; additional free space required during installation (cannot install on a volume that uses a case-sensitive file system or on removable flash storage devices)
    1024x768 display (1280x800 recommended) with 16-bit color and 512 MB of VRAM (1 GB recommended)**
    OpenGL 2.0–capable system
    Internet connection and registration are necessary for required software activation, membership validation, and access to online services.*
    ** 3D features are disabled and some Mercury Graphics Engine enhanced features may not work with less than 512 MB VRAM. Read the Help article.
    Bottom line, you don't have enough VRAM
    Nancy O.

  • Why can't we use iTunes gift cards with family sharing? After Christmas, we now have lots of account credit we can't use. Very frustrating.

    Why can't we use iTunes gift cards with family sharing? After Christmas, we now have lots of account credit we can't use. Very frustrating. There is no option found for using account credit.

    I just logged out of my daughter's account and back in, and now it works. Deducted from gift card account balance. So I hope this is resolved.

  • HT4061 Why can't I use face time on 3G internet

    Why can't I use FaceTime on 3G internt

    This feature will only be available when the new update ios6 comes out in sept or october and will only be for the iphone 4s or the new ipad if havent got one of these devices then facetime will only work over wifi the reason apparently the older devices are unable to handle it requires more processing power.

  • Hi, why can't I use the iMessage on my iPhone? I've already had my apple id email on it but it keeps saying "waiting for activation" always like that. No progress. Could anybody help me on this? Cheers

    Hi, why can't I use the iMessage on my iPhone? I've already had my apple id email on it but it keeps saying "waiting for activation" always like that. No progress. Could anybody help me on this? Cheers

    I have an old iPod Touch with old software that can no longer be updated:
    iOS version 6.1.6
    I've been searching for a solution to my iMessage login problem for months and tried everything from those frustrating links and all the tips from other users.
    Here is what finally worked:
    1) Settings > Privacy > Location Services > On
    2) Settings > General > Date & Time > Set Automatically > On
    3) Reboot device until Apple logo appears
    4) Settings > Messages > Sign In

  • Why can't i use my visa on my iphone ?

    why can't i use my visa card?

    I dont know?  what happens when you try?  visa is an acceptable payment method.

  • Why can't I use Emoji keyboard on my IOS7?, Why can't I use Emoji keyboard on my IOS7?, Why can't I use Emoji keyboard on my IOS7?

    Why can't I use the Emoji keyboard on my IPad Air?

    u need to set up 1st the Emoji keyboard. How ?
    setting>keyboard>keyboards>Add new keyboard>select Emoji

Maybe you are looking for