检查一个通用T是否实现了一个接口 [英] Check if a generic T implements an interface
问题描述
所以我在Java中有这个类:
public class Foo< T> {
}
在这个类里面我想知道T是否实现了某个接口。
以下代码不工作,但它是我想要完成的想法:
if(T。 class implements SomeInterface){
// do stuff
}
以检查传递给Foo的类 T
是否在其签名上实现了SomeInterface c>
有可能吗?如何?
通用,奇怪的是,使用 extends
1 您将需要使用:
public class Foo< T extends SomeInterface> {
//根据需要使用T
}
对于true / false检查,使用无界泛型( Foo< T> {
),并确保您获得类< T>
,因此您具有可折旧类型:
如果(SomeInterface.class.isAssignableFrom(tClazz));
其中 tClazz
code> java.lang.Class< T> 。
如果你得到一个refiable类型的参数, :
if(tParam instanceof SomeInterface){
但这不适用于通用声明。
1 需要扩展一个类和多个接口,你可以做如下:
< T extends FooClass& BarInterface& Baz>
类(只有一个,因为在Java中没有多重继承)必须先 ,之后的任何接口。so I have this class in Java:
public class Foo<T>{ }
and inside this class I want to know if T implements certain interface.
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 haveimplements SomeInterface
on its signature.Is it possible? How?
解决方案Generics, oddly enough, use
extends
for interfaces as well.1 You'll want to use: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 aClass<T>
so you have a refiable type:if(SomeInterface.class.isAssignableFrom(tClazz));
where
tClazz
is a parameter of typejava.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.
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.这篇关于检查一个通用T是否实现了一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!