| Author |
passing generic type to some method
|
B Nirvan
Ranch Hand
Joined: Oct 20, 2010
Posts: 82
|
|
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
Joined: Sep 28, 2004
Posts: 16811
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
B Nirvan
Ranch Hand
Joined: Oct 20, 2010
Posts: 82
|
|
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
Joined: Oct 27, 2005
Posts: 19232
|
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Yuriy Fuksenko
Ranch Hand
Joined: Feb 02, 2001
Posts: 413
|
|
you can try something like this:
http://gafter.blogspot.com/2006/12/super-type-tokens.html
here is the small example
|
 |
 |
|
|
subject: passing generic type to some method
|
|
|