Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Class.forName usage" Watch "Class.forName usage" New topic
Author

Class.forName usage

bob walker
Greenhorn

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");
myClass.implementedAbstractMethod(data);
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
Bartender

Joined: Feb 26, 2001
Posts: 4447
    
    5

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

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


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

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
 
Similar Threads
Groovy and Polymorphism
Dynamic polymorphism and memory allocation for object
Help reqd in reflection API
How to get the class name of the subclass from a static method in the superclass?
Abstract Inner Classes