This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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 Java 8 in Action this week in the Java 8 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: 4419
    
    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
Help reqd in reflection API
Abstract Inner Classes
How to get the class name of the subclass from a static method in the superclass?
Dynamic polymorphism and memory allocation for object