[英]Check if a generic T implements an interface
so I have this class in Java: 所以我在Java中有这个类:
public class Foo<T>{
}
and inside this class I want to know if T implements certain interface. 在这个类里面我想知道T是否实现了某个接口。
The following code DOES NOT work but it's the idea of what I want to accomplish: 以下代码不起作用,但它是我想要完成的想法:
if(T.class implements SomeInterface){
// do stuff
}
so I want to check if the class T
that was passed to Foo have implements SomeInterface
on its signature. 所以我想检查传递给Foo的类
T
implements SomeInterface
在其签名上implements SomeInterface
。
Is it possible? 可能吗? How?
怎么样?
Generics, oddly enough, use extends
for interfaces as well. 奇怪的是,泛型也
extends
了接口。 1 You'll want to use: 1你想要使用:
public class Foo<T extends SomeInterface>{
//use T as you wish
}
This is actually a requirement for the implementation, not a true/false check . 这实际上是实现的要求, 而不是真/假检查 。
For a true/false check, use unbounded generics( class Foo<T>{
) and make sure you obtain a Class<T>
so you have a refiable type: 对于真/假检查,使用无界泛型(
class Foo<T>{
)并确保获得Class<T>
因此您有一个可反复的类型:
if(SomeInterface.class.isAssignableFrom(tClazz));
where tClazz
is a parameter of type java.lang.Class<T>
. 其中
tClazz
是java.lang.Class<T>
类型的参数。
If you get a parameter of refiable type, then it's nothing more than: 如果你得到一个可反复类型的参数,那么它只不过是:
if(tParam instanceof SomeInterface){
but this won't work with just the generic declaration. 但这不仅适用于通用声明。
1 If you want to require extending a class and multiple interfaces, you can do as follows: <T extends FooClass & BarInterface & Baz>
The class(only one, as there is no multiple inheritance in Java) must go first , and any interfaces after that in any order. 1如果你想要扩展一个类和多个接口,你可以这样做:
<T extends FooClass & BarInterface & Baz>
这个类(只有一个,因为在Java中没有多重继承)必须先行 ,并且任何接口之后以任何顺序。
you can check it using isAssignableFrom 你可以使用isAssignableFrom来检查它
if (YourInterface.class.isAssignableFrom(clazz)) {
...
}
or to get the array of interface as 或者获取接口数组
Class[] intfs = clazz.getInterfaces();
Use isAssignableFrom()
使用
isAssignableFrom()
isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. isAssignableFrom()确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是它们的超类或超接口。
if (SomeInterface.class.isAssignableFrom(T class)) {
//do stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.