What is actually do class.forname

hi
experts
what is actually mean when we write
class.forName("sun.jdbc.odbc.....")
what actually does class.forName
plz give me a code to connect with mysql database on linux.

no, it doesn't. will people please please please
stop telling other people this. it's
completely wrong.It is?
Then why does the API documentation claim that "a
call to forName("X") causes the class named X to be
initialized?"
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Clas
s.html#forName%28java.lang.String%29because I misread "initialized" for "instantiated" in the above post! sorry! usually when this question comes up, the stock answer is "it instantiates the class"
my mistake

Similar Messages

  • What to do with Class.forName(), Class.getName() when Obfuscating

    hi,
    I have been asked at my company to perform Obfuscation of our project-code, The problem I have been facing is,
    We have got too many Class.forName(), Class.getName() calls in our Project-code, which is really hindering the process of Obfuscating all the Classes (refrences in code may break for all these classes which are dynamically being asked for, hence the project may suffer). And it is a pain-in-neck to really resolve which classes to exclude so that code should not break after obfuscation.
    What my question is:
    Do we have some automated tool to take care of all these Reflection API calls, so that work left to us is minimal?
    If not, Do we have some short-cut (program, tool etc.) to identify all the classes which should be excluded?

    Which program are you using when obfuscating?
    In RetroGuard you can for example avoid certain class names, or packages, to be obfuscated.

  • Diffrence between Class.forName() and new Operator

    What is diffrence between class.forName() and new operator.Please tell in much detail.
    Also about classloader.loadclass.
    Suppose the class that we are tring to load with the help of class.forname is not compiled. Again if I make changes at runtime to that class will that get reflected.

    What is diffrence between class.forName() and new
    operator.Please tell in much detail.Class.forName loads a class. The new operator creates a new instance. Apple trees and apples.
    Also about classloader.loadclass.Read the API.
    Suppose the class that we are tring to load with the
    help of class.forname is not compiled.Then you can't load it and get an exception. Read the API.
    Again if I
    make changes at runtime to that class will that get
    reflected.Depends on the changes and when exactly you do them.

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

  • What is the Difference between ?  new Operator and Class.forName() ???

    plz tel me ....
    what is the Difference between ? new Operator and Class.forName() ??? ........

    Class.forName(), takes the class name as parameter,
    and loads that class in memory. But it doesn't create
    any instance of that class.
    That means static methods/variables are available for
    use.
    new keyword, checks if the class is loaded, if not
    then loads that class, and then creates an instance
    of that class.Class.forName actually returns the class object for that name (class - for -name). it might load it, if the class hasn't already been loaded, but it's misleading to say that's what that method does
    your definition of 'new' is wrong, too. give the dukes back

  • What is actually happenning when we are importing a class of some other pac

    Sirs,
    I have a doubt which is very basic to java,
    I want to import a class say "HashMap" to my class.
    If i put import "java.util.HashMap" or "import java.util.*;"
    Which will be better ?
    If i put "import java.util.*; " will it affect the performance?
    What is actually happenning when we are importing a class of some other package to our class
    Your help solicited,
    Sudheesh K S

    Many of your questions of this nature can be quickly answered by a search of prior posts to the forums, like this:
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=631979
    And why do you tend to post boldened text? It's harder to read.

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

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

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

  • Need a clear explanation for class.forName()

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
    Connection conn = DriverManager.getConnection("aadsn","xxxxx","xxxx");
    actually what it does behind the scene.

    (Copied from http://forum.java.sun.com/thread.jsp?forum=48&thread=471358)
    Class.forName() loads the given class. In itself, that isn't interesting. The beef lies in that loading a class executes any static blocks in that class.
    If you had the source to com.mysql.jdbc.Driver, it would probably start something like:
    public class Driver
        static {
            Driver driver_object = new Driver();
            java.sql.DriverManager.registerDriver(driver_object);
    }The static block does the actual work of registering the driver. Class.forName() is really just a bit of a hack to get that static block executed.
    The newInstance() call is customary because there is an old rumor that some buggy JDBC driver somewhere is missing the static block, and has the registerDriver() call in a Driver() object constructor instead. A belt and suspenders kind of thing.
    If you want to see real life examples of that static block, google around for open source JDBC drivers.

  • Class.forName("X")

    Guys,
    Can someone please explain what Class.forName("X") really does. I read the JavaDocs which mentions this:
    A call to forName("X") causes the class named X to be initialized.
    What does initialize really mean? I thought it would call the X( ) (Default Constructor of class X but doesn't seem like it)
    TIA

    Guys,
    Can someone please explain what
    explain what Class.forName("X") really does. I read
    the JavaDocs which mentions this:
    A call to forName("X") causes the class named X to be
    initialized.
    What does initialize really mean? I thought it would
    call the X( ) (Default Constructor of class X but
    doesn't seem like it)Initializing the class is not the same as instantiating and initializing an object (i.e. an instance) of that class.
    Say you write two classes, Foo and Bar. You put your main in Foo, and Foo creates a Bar and does some stuff with it: public void main(String[] args) {
        System.out.println("Hello");
        Bar bar = new Bar();
        bar().doStuff();
    } At the point where you're printing out "Hello", the VM doesn't yet know anything about the Bar class. Only on the next line, where it actually has to do something with Bar does it search the classpath, find Bar.class, load the class (read the bytes of the .class file into memory) and initialize the class (create its static members, run its static initializers, if any, other stuff that's detailed in the JLS and/or VM spec).
    Calling Class.forName() is a way to force the VM to load and initialize the class just like it would upon first encountering a usage of that class in your code.

  • Class.ForName, is it possible?

    if a class has not been compiled, in other words, the class is only a name in .java file, could we use Class.ForName to get its information?
    if not, is there any other idea to get the class info from .java file? -- i mean, not open the jave file as buffer to read what text is on it - is there a method similar to Class.ForName in the case?
    thx

    if a class has not been compiled, in other words, the
    class is only a name in .java file, could we use
    Class.ForName to get its information?No. Class.forName only works on compiled classes within the classpath.
    if not, is there any other idea to get the class info
    from .java file? -- i mean, not open the jave file as
    buffer to read what text is on it - is there a method
    similar to Class.ForName in the case?If your question is how to get class info by not compiling it one,
    and not reading the .java source file two, the answer again is no.
    Simply because the demand is unreasonable.
    If your question is Is there any helper class to read .java
    source file and give back the class info, the answer is yes. And
    the java compiler is exactly what this helper class is. Do you know
    javac is actually a java program, and in turn it is a java
    class?
    Let me know if this is what you are looking for and need more info
    on how to compile a java file inside another class.
    --lichu

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

  • Applet - Class.forName..

    I have an applet which is loading fine but my combo boxes aren't getting populated - I'm getting "Failed to load JBDC/ODBC driver" because of the following:
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(Exception e){
    System.out.println("Failed to load JBDC/ODBC driver");
    Any ideas?
    Jacintha

    What are you actually trying to do? Are you connecting through a Servlet/JSP or is it a standalone applet? Seems like you are using Windows. Use ODBC Datasources in the Control Panel to set a DSN. Which database are you using? Which Platform are you working on and what is the objective of your applet?
    I have an application and when you click a particular button on a jsp - you are directed to the html file that loads the applet. I'm using an Oracle database. When the applet loads ( a swing applet) the buttons etc comes up but the combo boxes are not populated - should be populated from the database - I have been looking through this forum and some have mentioned to sign the applet - I am in the process of doing this - I don't know if you know anything about this. I have got as far as signing the jar file and exporting the public key certificate - but now it goes into details about the code receiver which I'm getting puzzled about. I am using the following site: http://java.sun.com/docs/books/tutorial/security1.2/toolsign/index.html. I don't know what direction to go now!

Maybe you are looking for

  • Tried to send a picture, now can't text this ONE p...

    i'm on Windows (XP), he's on a Mac. i tried to send a pic that was actually from an online e-mail attachment, twice; he accepted, but got nowhere. then, i realized my mistake, downloaded the pic, and tried to send that -- but that didn't work. now, S

  • Assign error with complex type return message

    Dear all, I have an axis web service with complex type return message. When I invoke the web service, and try to assign one element of the result to other variable, it fails with following error message(BPEL Fault:{http://schemas.xmlsoap.org/ws/2003/

  • Financial Reports 9.3.1.3 Client

    I am having problems connecting FR Client (9.3.1.3) with FR Server (9.3.0.1). Is it possible to connect to the server with a newer version of the client. I get an "Unknown Error" Brian Chow

  • System refresh - RSA7 is now empty.

    Hi, After a system refresh of all our QA systems, all delta queues in the source systems, are empty. Do we need to re-initialize them again? Did this on one of the datasources but the delta queue was still empty and ofcourse no records moved to the B

  • Installing java3d opengl version?

    i have my java j2sdk1.4.2_04 installed in the root of c: i have j2re1.4.2_03 installled in the following location C:\Program Files\Java i installed the java3d-1_3_1-windows-i586-opengl-sdk package, and when it asked for my install directories, it aut