File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Class.forname" Watch "Class.forname" New topic
Author

Class.forname

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
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

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.
hth,
bear
[ November 07, 2002: Message edited by: Bear Bibeault ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Jim Yingst
Wanderer
Sheriff

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: http://aspose.com/file-tools
 
subject: Class.forname