Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class and Generics ?

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic