Java – generic methods for non generic classes

I try to use a generic approach, so I don't have to repeat the code I tried:

private Listener createListenerAdapter(Class<T> clazz)
{ 
   // do something
}

Clazz is important because class is reserved

But NetBeans complained, "the symbol class T cannot be found."

I'm going to pass several different classes that have the same method Where should I define t?

Solution

The declaration method is:

private <T> Listener createListenerAdapter(Class<T> clazz)

For more information, see Java tutorials

Edit: if t is not related to the return type, you can also use wildcards:

private Listener createListenerAdapter(Class<?> clazz)

Edit 1: if clazz is intended to represent a listener type, you can define boundaries to limit callers (to avoid conversions and potential runtime exceptions):

private <L extends Listener> L createListenerAdapter(Class<L> clazz)

Or wildcards:

private Listener createListenerAdapter(Class<? extends Listener> clazz)

But it depends on what kind of clazz is used in the human body

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>