Java:instanceof Generic [英] Java: instanceof Generic

查看:117
本文介绍了Java:instanceof Generic的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if(T instanceof String){ 
//做某事...
}

以上绝对不会编译。

解决方案

泛型是一个编译时功能。泛型在编译时添加检查,这在运行时可能没有任何意义。这是一个例子。您只能检查可能是代码中超级类型的引用对象的类型。如果你想传递类型T,你必须明确地做到这一点。

  void someMethod(Class< T> tClass){
if(String.class.isAssignableFrom(tClass))

  void someMethod(Class< T> tClass,T tArg){

注意:类型可能不一样,

  someMethod(Number.class,1 ); 


Isn't there any way to find the class-type of a generic?

if (T instanceof String) {
    // do something...
}

The above definitely does not compile.

解决方案

Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.

void someMethod(Class<T> tClass) {
    if(String.class.isAssignableFrom(tClass)) 

or

void someMethod(Class<T> tClass, T tArg) {

Note: the type might not be the same,

someMethod(Number.class, 1);

这篇关于Java:instanceof Generic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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