I am not familiar with class.forName but from my reading tonight it looks as though you would only use it in specific settings where you absolutely need it.
Check out [url=http://rds.yahoo.com/_ylt=A0geu7dN319Gh7AAM8tXNyoA;_ylu=X3oDMTB2ZHEzZ2FsBHNlYwNzcgRwb3MDMwRjb2xvA2UEdnRpZAMEbANXUzE-/SIG=12h1laial/EXP=1180774605/**http%3a//www.javageeks.com/Papers/ClassForName/ClassForName.pdf]this article[/url].
Class.newInstance() allows you to create an instance of a class dynamically, i.e. you don't know the type in advance.
However there are also patterns for that (such as Prototype and Factory), so it's not needed so often.
One case where class.newInstance() is useful is in plug-in type situations where you cast the class to an interface it implements, you know the interface at compile time, but the actuall class type is unknown.
> I am not familiar with class.forName but from my
> reading tonight it looks as though you would only use
> it in specific settings where you absolutely need
> it.
>
Class.forName() causes the classloader to load the class in preparation for instantiating it, nothing more nothing less.
Can be useful in some scenarios, but not all that often.
> Class.forName() causes the classloader to load the class in preparation for instantiating it
Yes and this causes the static initialisation code in the class to run.
Likeclass LoadThisClass
{
private static string text = "hi";
static {
System.out.println(text);
}
}
> > yes.. i think it returns Class object. But, is
> there
> > any other way to instantiate a class other than
> using
> > the new operator
>
> Others
> - JNI, similar but not exactly new
> - Serialization which by passes the normal process
Cloning
Class.newInstance has been mentioned, but Constructor.newInstance has not