[英]Generic Method in Non-Generic Class
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). (
clazz
很重要,因为class
是保留的)。
But Netbeans complains that : "Cannot find symbol class T". 但Netbeans抱怨说:“找不到符号类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?
我应该在哪里定义T?
Declare the method as: 将方法声明为:
private <T> Listener createListenerAdapter(Class<T> clazz)
See the Java Tutorials for more information. 有关更多信息,请参阅Java教程 。
Edit: If T
isn't related to the return type you could also just use a wildcard: 编辑:如果
T
与返回类型无关,您也可以使用通配符:
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): 编辑1:如果
clazz
用于表示一种Listener
,您可以定义边界来限制调用者(以避免强制转换和潜在的运行时异常):
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. 但这取决于如何在身体中使用
clazz
。
Generic declarations can also be made at method-level by parametrizing them like this: 通用声明也可以通过参数化它们在方法级别进行,如下所示:
private <T> Listener createListenerAdapter(Class<T> clazz)
{
// do something
}
If you're not using the type (unlikely, but you may be trying to avoid a raw type warning): 如果您没有使用该类型(不太可能,但您可能尝试避免原始类型警告):
private Listener createListenerAdapter(Class<?> clazz)
{
// do something, without knowing the T of the clazz
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.