• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class.forName usage

 
bob walker
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 8754
78
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
bob walker
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that got me over that hurdle.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic