Java 检查泛型 T 是否实现了接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18783916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a generic T implements an interface
提问by Budius
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.
所以我想检查T
传递给 Foo的类是否有implements SomeInterface
其签名。
Is it possible? How?
是否可以?如何?
采纳答案by nanofarad
Generics, oddly enough, use extends
for interfaces as well.1You'll want to use:
奇怪的是,泛型也extends
用于接口。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:
对于真/假检查,使用 unbounded generics( class Foo<T>{
) 并确保您获得 aClass<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:
如果你得到一个 refiable 类型的参数,那么它无非是:
if(tParam instanceof SomeInterface){
but this won't work with just the generic declaration.
但这仅适用于通用声明。
1If 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中没有多重继承)必须先行,然后是任何顺序的任何接口。
回答by muthu
you can check it using isAssignableFrom
您可以使用 isAssignableFrom 来检查它
if (YourInterface.class.isAssignableFrom(clazz)) {
...
}
or to get the array of interface as
或获取接口数组为
Class[] intfs = clazz.getInterfaces();
回答by Naveen Kumar Alonekar
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
}