A short question about forName:
I have an interface called 'GeometryPainter' and a subclass that
implements it, which is called 'DefaultGeometryPainter'. I'm
instantiating the DefaultGeometryPainter as following (Java5):
Class painter = Class.forName(lpainterClass);
GeometryPainter gm = GeometryPainter.class.cast(painter);
It finds the class, because I don't get a ClassNotFoundException, but I
cannot cast it to GeometryPainter (it throws a ClassCastException). Can
someone tell me why? What should I do?
jeffcoat - 25 Sep 2006 18:35 GMT
> A short question about forName:
>
[quoted text clipped - 8 lines]
> I cannot cast it to GeometryPainter (it throws a
> ClassCastException). Can someone tell me why? What should I do?
You don't want a cast, you want to call Class.newInstance().
Something like ...
try {
Class painter = Class.forName("DefaultGeometryPainter");
GeometryPainter gm = (GeometryPainter) painter.newInstance();
} catch ...
If you want something other than the default constructor,
look into Class.getConstructor().

Signature
Mark Jeffcoat
Moiristo - 26 Sep 2006 00:12 GMT
> You don't want a cast, you want to call Class.newInstance().
>
[quoted text clipped - 7 lines]
> If you want something other than the default constructor,
> look into Class.getConstructor().
Thank you both, it's working now.
jagonzal@gmail.com - 25 Sep 2006 22:35 GMT
> A short question about forName:
>
[quoted text clipped - 8 lines]
> cannot cast it to GeometryPainter (it throws a ClassCastException). Can
> someone tell me why? What should I do?
This code: Class painter = Class.forName(lpainterClass);
Gives you the object that represents the _class_ of that object, not an
instance of the class.
For that you need to call newInstance() on the Class object (if you
have a no-argument constructor), or get the constructors, and call one
of them according to the parameters it takes.
Check the Class javadocs.