*
The moose likes Java in General and the fly likes passing generic type to some method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "passing generic type to some method" Watch "passing generic type to some method" New topic
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: 18498
    
  40



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: 19649
    
  18

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 - OCEEJBD 6
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

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing generic type to some method
 
Similar Threads
Self Written Code on Generic Problem
How far we can use Generics?
Question regading Generics
Need help creating arraylist of stacks
Varargs and arrays - Mughal's mock exam, question 60