检查泛型 T 是否实现了接口 [英] Check if a generic T implements an interface

查看:37
本文介绍了检查泛型 T 是否实现了接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 Java 中有这个类:

so I have this class in Java:

public class Foo<T>{
}

在这个类中我想知道 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
}

所以我想检查传递给 Foo 的类 T 是否在其签名上具有 implements SomeInterface.

so I want to check if the class T that was passed to Foo have implements SomeInterface on its signature.

有可能吗?怎么样?

推荐答案

奇怪的是,泛型也使用 extends 作为接口.1 你会想要使用:

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.

对于真/假检查,请使用无界泛型(class Foo{) 并确保您获得一个 Class 以便您有一个可重构的类型:

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:

if(SomeInterface.class.isAssignableFrom(tClazz));

其中 tClazzjava.lang.Class 类型的参数.

where tClazz is a parameter of type java.lang.Class<T>.

如果你得到一个 refiable 类型的参数,那么它无非是:

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如果你想需要扩展一个类和多个接口,你可以这样做:<T extends FooClass &酒吧界面 &Baz> 类(只有一个,因为在 Java 中没有多重继承)必须首先,之后的任何接口以任何顺序.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆