File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Class.forname Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Class.forname" Watch "Class.forname" New topic


Leandro Oliveira
Ranch Hand

Joined: Nov 07, 2002
Posts: 298
I tried to understand this by my own... I couldn't. then I tried:
JFrame frame=(JFrame)Class.forName("javax.swing.JFrame");
then it did not work;
after I tried:
JFrame frame=(JFrame)Class.forName("javax.swing.JFrame").newInstance();
after that I noticed that it was the same as
JFrame frame=new JFrame();
funny!!! but what does Class.forName do???
Sorry for the english... I'm from another country and I think my english is getting worse....
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63874

Let's say that, as an example, you read in the name of a class from a configuration file. Your program has no way of knowing what the class name is.
Through the use of Class.forName() you can create an instance of the class.
A good example of this is JSP custom tags. The class implementing the tag is named in the TLD file (an XML descriptor of the tag library), and the JSP container creates instances of the class as needed.
[ November 07, 2002: Message edited by: Bear Bibeault ]

[Asking smart questions] [About Bear] [Books by Bear]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I'm not sure if all your questions were answered. Just in case...
JFrame frame=(JFrame)Class.forName("javax.swing.JFrame");
This didn't compile, because Class.forName() returns a Class object, not a JFrame object. But you can create a JFrame instance from the Class using the newInstance() method of class, as you did in your second attempt.
[ November 07, 2002: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Leandro Oliveira
Ranch Hand

Joined: Nov 07, 2002
Posts: 298
thanks... I think that I did not understand because many books just order you to use class.forName to load a driver... they do not say what it does!!!
I agree. Here's the link:
subject: Class.forname
It's not a secret anymore!