Why generics for the Class type?

J

Josef Garvi

Why does the Class type use Generics?

Or in other words - how am I supposed to use it?
I store certain Classes in hash tables, and then create dynamic instances
of objects according to the correct type at run-time. What "type of class"
should my Class variables be??

--
Josef Garvi

"Reversing desertification through drought tolerant trees"
http://www.eden-foundation.org/

new income - better environment - more food - less poverty
 
J

John C. Bollinger

Josef said:
Why does the Class type use Generics?

Or in other words - how am I supposed to use it?
I store certain Classes in hash tables, and then create dynamic
instances of objects according to the correct type at run-time. What
"type of class" should my Class variables be??

It depends, but some way around you're going to need to use a wildcard
type parameter. Class<?> will definitely work, but you may be able to
use something more specific. For instance, if you are storing only
Class objects for classes that implement Serializable, you could use
Class<? extends Serializable>. You may indeed want to do this sort of
thing to achieve type safety and dispense with casting when you create
instances:

Class<? extends Serializable> clazz;

[...]

Serializable ser = clazz.newInstance(); /* typesafe; no cast required */
 
J

Josef Garvi

John said:
It depends, but some way around you're going to need to use a wildcard
type parameter. Class<?> will definitely work, but you may be able to
use something more specific. For instance, if you are storing only
Class objects for classes that implement Serializable, you could use
Class<? extends Serializable>. You may indeed want to do this sort of
thing to achieve type safety and dispense with casting when you create
instances:

Class<? extends Serializable> clazz;

[...]

Serializable ser = clazz.newInstance(); /* typesafe; no cast required */

Thanks. That's how I wanted it to work! :)

--
Josef Garvi

"Reversing desertification through drought tolerant trees"
http://www.eden-foundation.org/

new income - better environment - more food - less poverty
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top