How to use genericized Class class

H

hiwa

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.
 
C

Chris Smith

hiwa said:
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.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
T

Tony Morris

hiwa said:
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.

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/

--
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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top