Generic Method in Non-Generic Class
Solution 1
Declare the method as:
private <T> Listener createListenerAdapter(Class<T> clazz)
See the Java Tutorials for more information.
Edit: If T
isn't related to the return type you could also just use a wildcard:
private Listener createListenerAdapter(Class<?> clazz)
Edit 1: If clazz
is meant to represent a type of Listener
, you could define bounds to restrict the caller (to avoid casts and potential runtime exceptions):
private <L extends Listener> L createListenerAdapter(Class<L> clazz)
Or with the wildcard:
private Listener createListenerAdapter(Class<? extends Listener> clazz)
But that depends on how clazz
is used in the body.
Solution 2
Generic declarations can also be made at method-level by parametrizing them like this:
private <T> Listener createListenerAdapter(Class<T> clazz)
{
// do something
}
Related videos on Youtube
Admin
Updated on August 23, 2022Comments
-
Admin over 1 year
I am trying to use a generic method so I don't have to repeat code. I have tried:
private Listener createListenerAdapter(Class<T> clazz) { // do something }
(
clazz
being important becauseclass
is reserved).But Netbeans complains that : "Cannot find symbol class T".
I am going to be passing in a few different classes that have the same methods on them. Where am I supposed to define T?
-
Admin over 11 years
clazz
is a GUI widget in GWT. -
Paul Bellora over 11 yearsOkay, so probably
Class<? extends Widget>
is the best fit. -
Admin over 11 yearsIs there a way to call a method on
clazz
inside createListenerAdapter() that corresponds to a method inside the class? So if I pass inButtonWidget
I want to be able to callclazz.setEnable(true)
. All widgets have the same method call. I am passing inButtonWidget
ascreateListenerAdapter(myWidget.getClass());
clazz.setEnable(true)
does not work because it thinks I am asking for a method onClass<?>
-
Paul Bellora over 11 years
setEnable
is an instance method right? You would need to useclazz
to instantiate a newWidget
and then call the method on it. -
Admin over 11 yearsYes, it is an instance method. I have several classes that derive from the same superclass, but is there a way to tell which subclass was passed in? I tried
Class<? extends MySuperClass>
but that doesn't give me the subclass. There are several different subclasses. -
Paul Bellora over 11 yearsWell the idea behind polymorphism is that you shouldn't have to know. If they share a common interface/superclass you can just treat them all like that and not worry about their implementation details.
-
Paul Bellora over 11 years