I am new to java class loading. In using it, I have two questions based
on the following code:
Class cc = Class.forName("G2");
G2 g = (G2)cc.newInstance();
1. When calling newInstance() to initialize "g", should G2 have to have
a default constructor without any parameters (i.e. public G2() {...}) ?
If yes, is there anyway to get around this if every G2's constructor
has at least one parameter? If no, how to call newInstance() in a
proper way?
2. What if G2 is a Java Generic class, e.g., G2<String, Int>? I tried
it. Except some "parameterize" warning messages at compile time, it
works fine. But my question is, is it safe?
Thanks.
oulan bator - 27 Jan 2006 19:35 GMT
hi,
1- yes of course, but you can get through this, using the
getConstructor() see
(http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getDeclaredConstruc
tor(java.lang.Class...))
2- I don't know, but I would like to kown
Thomas Hawtin - 27 Jan 2006 19:35 GMT
> Class cc = Class.forName("G2");
> G2 g = (G2)cc.newInstance();
[quoted text clipped - 4 lines]
> has at least one parameter? If no, how to call newInstance() in a
> proper way?
Get a Constructor from the Class and call newInstance on that.
Class.newInstance should be avoided anyway because of its eccentric
exception behaviour.
> 2. What if G2 is a Java Generic class, e.g., G2<String, Int>? I tried
> it. Except some "parameterize" warning messages at compile time, it
> works fine. But my question is, is it safe?
It's a good idea to avoid using generic types in this sort of situation.
Kind of difficult with serialisation, but such is life.
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/