Class.forName()?
Hi All,
what exactly does a statment
Class.forName("java.lang.String") does?
Will it create a new object of class String?
What actions does it perform inside JVM once such a statment is called?
What does Class s = Class.forName("java.lang.String") ;
will do?
TIA
Ayusman
Hi,
When u r using the Class.forName("");
it will loads the class dynamically,at that time there is no class file then it will throws Class not found Exception.
The below program explain this
class Test
{
public static void main(String args[])
Class cs=Class.forName("temp");//here temp is class file
((temp)cs.newInstance()).m1;//here m1 is temp class method
}//main
}//class
in ur directory temp.class file is not exist ClassnotFoundException
will raises
as the other poster said, it loads a class at runtime. basically, classes exist in memory, waiting to be instantiated, because the runtime loaded them when it started. often, you won't know exactly what classes your application will use when you're writing and compiling it, so Class.forName is one way to get round this. if you package up some classes in a jar, and drop that jar onto the classpath while your application is running, Class.forName is one way to get at those classes and use them in your application. think of how you don't need to shut down and re-start Tomcat in order to deploy a new web app to it. that's done through dynamic classloading, although I highly doubt it's done using Class.forName
[url=http://java.sun.com/j2se/1.3/docs/api/java/lang/Class.html#forName(java.lang.String)]Class.forName [/url]returns the [url=http://java.sun.com/j2se/1.3/docs/api/java/lang/Class.html]Class[/url] object for the given string (or throws a ClassNotFoundException). This can be used in [url=http://java.sun.com/docs/books/tutorial/reflect/index.html]Reflection[/url], or to guarantee a class has been loaded by the JVM.
> Will it create a new object of class String?
No it will create a Class object for type String.
> What actions does it perform inside JVM
> once such a statment is called?
Have I loaded class X
if not
Load it
fi
return Class object
mlka at 2007-7-13 23:18:45 >

> > Have I loaded class X
> if not
>Load it
> eturn Class object
>
more accurately
Have I loaded class X
if not
Has my immediate parent loaded class X? if so
return it
else
Load it
return Class object
pseudo-bytecode. nice :-)
> more accurately
> >
> Have I loaded class X
> f not
> Has my immediate parent loaded class X? if so
>return it
>
>Load it
> rn Class object
>
>
> pseudo-bytecode. nice :-)
Erm.. no actually. A classloader will load a class only if the parent can't load it, not if the parent could load it, but hasn't. Hence your typically URLClassLoader won't load a class itself if a class of the requested name is on the class path.