Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android forum!
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: 60789
    
  65

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!!!
 
 
subject: Class.forname
 
Similar Threads
Problem with Graphics
MODAL JFRAME
i have a jfarame. i want to call a existing from when i click close button[default close button]
Handling exceptions in a MDI application?
JDialog modality issue on Win7 taskbar click