In the pre-generics era, we did:
Class claz = Class.forName("Foo");
Foo foo = (Foo)(claz.newInstance());
We anticipate we can be freed from casting by generics:
Class<Foo> claz = Class.forName("Foo"); // line 1
Foo foo = claz.newInstance();
But compiler emits 'incompatible types' error for the line 1 above.
We try another:
Class<Foo> claz = (Class<Foo>)(Class.forName("Foo")); // line 1
Foo foo = claz.newInstance();
Then, compiler emits 'unchecked cast' warning for the line 1 above.
What should be the correct syntax for getting a Class<Foo> object
from the forName() method without errors nor warnings?
Thanks in advance.
Chris Smith - 07 May 2005 04:05 GMT
> What should be the correct syntax for getting a Class<Foo> object
> from the forName() method without errors nor warnings?
You can't. Generics allow you to avoid casts in situations where the
compiler can check that type safety is preserved. In cases like that
above where no such compiler check is possible, the cast is just as
necessary as it always was.
On the other hand, a literal like:
Class<Foo> clz = Foo.class;
Foo f = clz.newInstance();
will work fine, since the Class<Foo> type is compiler-checked.

Signature
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
Tony Morris - 07 May 2005 07:38 GMT
> In the pre-generics era, we did:
>
[quoted text clipped - 18 lines]
>
> Thanks in advance.
final Class<?> c = Class.forName(x);
if(Foo.class.isAssignableFrom(c))
{
Class<Foo> cf = c.asSubclass(Foo.class);
}
Take a look at the JTiger source code for more examples.
http://www.jtiger.org/

Signature
Tony Morris
Software Engineer, IBM Australia.
BInfTech, SCJP 1.4, SCJD
http://www.jtiger.org/ JTiger Unit Test Framework for Java
http://qa.jtiger.org/ Java Q&A (FAQ, Trivia)
http://xdweb.net/~dibblego/