Class.forName is used to dynamically "load" a class. Its predominently used to load jdbc drivers. In this way loading and creating an instance of a class can be deferred to runtime. Whereas creating an instance using "new" operator requires that the class name be known at compile time itself. [ September 15, 2003: Message edited by: Lakshmi Dasari ]
Be aware that there is a clear distinction between the loading of a class, which may be triggered when one of its static methods is invoked, and the instantiation of a class with the new keyword. It is quite possible, and in some cases highly desirable, to have a class loaded but never instantiated.
To be a bit clearer, Class.forName("java.lang.String") is the exactly same is writing: java.lang.String.class . So, if you understand the difference between "String.class" and "new String()" then you should be able to answer the question.
As described above, the "new" method requires that the class name be known at compile time and creates an instance, whereas forName is used at runtime and only loads a class. This is not just useful for jdbc drivers, it is useful for whenever you want to specify a class name dynamically. e.g. on initializing a web app, you could read the names of classes as parameters and load them via forName. This enables different implementations to be used without code changes.
forName also allows specification of the class loader and whether the class is initialized.
forName requires a no-parameter constructor. If you want to dynamically create a class with a more complex constructor, you need to dive deeper into reflection. Here's a little Interpreter project that goes all the way. For those of us who think typed langauges are a good thing because they let the compiler catch more errors, dynamic creation is not something we do lightly. Errors like incorrect classnames might be introduced in the field by configuration typos. But it can be way cool. I'm writing a web server now with plug-in macro processors - just give the classname in the configuration and I create a singleton at startup.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Sep 15, 2003
thanks all for the replies !! regards, sonalee
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com