| Author |
Class and Generics ?
|
Edward Chen
Ranch Hand
Joined: Dec 23, 2003
Posts: 758
|
|
if I only have a Class, how to use generics ?
Like this....
But this can't pass compiler, how to work out ?
Thanks
|
 |
Gavin Tranter
Ranch Hand
Joined: Jan 01, 2007
Posts: 333
|
|
Hi,
Generics uses Type information not the names of instances.
Type information is the name of a class, suct as String or 2DPoint.
Therefore in your example you should replace myClass with Class, as Class is the type of the objects you plan to store in the list.
hope this helps
Gavin
|
 |
Edward Chen
Ranch Hand
Joined: Dec 23, 2003
Posts: 758
|
|
Gavin Tranter wrote:
Therefore in your example you should replace myClass with Class, as Class is the type of the objects you plan to store in the list.
Are you saying
List<Class> peopleList = (List<Class>)anotherList;
But this can't help me. My goal is to dynamically cast a list to another list based on its Class type.
The perfect solution for me will be something like this
How to work out ?
Thanks.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24040
|
|
|
Generics are a compile-time only construct. At runtime, a List contains only Objects; therefore your request really doesn't make any sense; is it not necessary.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Mike Simmons
Ranch Hand
Joined: Mar 05, 2008
Posts: 2770
|
|
|
This isn't exactly what you asked for, but you might like Collections.checkedList(). It's not "casting" , but it creates a list that can only contain the specified type. Unless the list already contained some other type within it, in which case you'll get a ClassCastException if you try to access it.
|
 |
 |
|
|
subject: Class and Generics ?
|
|
|