Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing generic type to some method

 
B Nirvan
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a class that looks this

I want to call a Generic method of another class, passing it the type information of the above class. I tried E.class, but compiler doesn't allow that(and shouldn't allow because E doesn't exist at runtime. How do I pass E type to a generic method then.

regards,
Nirvan.
 
Henry Wong
author
Marshal
Pie
Posts: 20998
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Do you happen to have an instance of type E? If you do, you can call the getClass() method. Otherwise, no, it's not possible.

Henry
 
B Nirvan
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't have an instance of E. I will have to force the client of this generic class to pass a dummy instance of E in the constructor. Thanks very much for reply.

regards,
Nirvan.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd require a Class<E> instead. That allows you to use Integer.class etc - so you won't need to initialize the class for every call.
 
Yuriy Fuksenko
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can try something like this:
http://gafter.blogspot.com/2006/12/super-type-tokens.html

here is the small example

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic