Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) 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
Sheriff
Posts: 22610
111
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
Posts: 20827
68
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

 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!