Generic Method in Non-Generic Class

10,176

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
}
Share:
10,176

Related videos on Youtube

Admin
Author by

Admin

Updated on August 23, 2022

Comments

  • Admin
    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 because class 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
    Admin over 11 years
    clazz is a GUI widget in GWT.
  • Paul Bellora
    Paul Bellora over 11 years
    Okay, so probably Class<? extends Widget> is the best fit.
  • Admin
    Admin over 11 years
    Is there a way to call a method on clazz inside createListenerAdapter() that corresponds to a method inside the class? So if I pass in ButtonWidget I want to be able to call clazz.setEnable(true). All widgets have the same method call. I am passing in ButtonWidget as createListenerAdapter(myWidget.getClass()); clazz.setEnable(true) does not work because it thinks I am asking for a method on Class<?>
  • Paul Bellora
    Paul Bellora over 11 years
    setEnable is an instance method right? You would need to use clazz to instantiate a new Widget and then call the method on it.
  • Admin
    Admin over 11 years
    Yes, 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
    Paul Bellora over 11 years
    Well 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
    Paul Bellora over 11 years