wood burning stoves
The moose likes Beginning Java and the fly likes Class.forName usage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Class.forName usage" Watch "Class.forName usage" New topic

Class.forName usage

bob walker

Joined: Feb 20, 2001
Posts: 14
I'm trying to use Class.forName to give me one of several
named classes.
I have a parent Abstract class that has a common abstract
method that each child implements.
When I try:
ParentClass myClass = Class.forName("childClassString");
The compiler gives me a "type mismatch" error.
When I change ParentClass to Class then I get a "method not defined" error.
I've tried casting but it doesn't appear to clear my problems.
Any clues anyone?
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

This should work:
Class c = Class.forName("childClassString");
Parent o = (Parent)c.newInstance();

Note that your child class should have a no-argument constructor for the c.newInstance() to work.
[This message has been edited by JUNILU LACAR (edited June 05, 2001).]

Junilu - [How to Ask Questions] [How to Answer Questions]
bob walker

Joined: Feb 20, 2001
Posts: 14
Thanks, that got me over that hurdle.
I agree. Here's the link: http://aspose.com/file-tools
subject: Class.forName usage
jQuery in Action, 3rd edition