tags:

views:

133

answers:

2

Basically I want to create a method that has a signature like the following:

public <T> T getShellTab(Class<T extends ShellTab> shellTabClass)

but this isn't valid Java.
I want to be able to pass a class that is a subclass of ShellTab and have an instance of that class returned.

public <T> T getShellTab(Class<T> shellTabClass)

works fine, but I would like to force shellTabClass to be a subclass of ShellTab.

Any ideas on how to pull this off?

Thank you.

+10  A: 

Put the constraint in the initial generic parameter, like this:

public <T extends ShellTab> T getShellTab(Class<T> shellTabClass)

Note that you can have constraints on the generic type parameters of the method parameters (for instance, Tom Hawtin - tackline suggests making shellTabClass into a Class<? extends T>, although I don't think it makes a difference in this case).
But you can't constrain a type that has already been declared.

Michael Myers
Probably public <T extends ShellTab> T getShellTab(Class<? extends T> shellTabClass).
Tom Hawtin - tackline
Does that buy anything over what I posted? T could be any subclass of ShellTab anyway, right?
Michael Myers
D'Oh! Its so simple now! Awesome, that works great thank you.
Sandro
+2  A: 

How about this?

public <T extends ShellTab> T getShellTab(Class<T> shellTabClass)