在泛型方法中使用instanceof [英] Usage of instanceof in a generic method

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

问题描述

我今天开始学习泛型,但这对我来说有点奇怪:



我有一个通用方法:

  public< T> HashMap< String,T> getAllEntitySameType(T type){

System.out.println(type.getClass());
HashMap< String,T> result = null;

if(type instanceof Project)
{
System.out.println(type.toString());
System.out.println(Yes,Project of instance;);


if(type instanceof String)
{
System.out.println(type.toString());
System.out.println(Yes,String of instance;);
}
this.getProjects();
返回结果;
}

我可以很容易地确定T类型的类型

 项目< Double> project = new Project< Double>(); 
company2.getAllEntitySameType(project);
company2.getAllEntitySameType(TestString);

输出结果如下:

  class Project 
是,Project的实例;
class java.lang.String
TestString
是,String的实例;

我认为在泛型中我们不能使用实例。据我所知,有些东西不完整。谢谢...

解决方案

您可以使用 instanceof 来检查<例如项目

  


$ b

如果(类型为instanceof Project)
或者使用 Project 某些未知类型:

  if(type instanceof Project<?>)

但是你不能 reify 参数化类型,如 Project< Double> with instanceof ,由于类型擦除

  if(type instanceof Project< Double>)//编译错误

正如Peter Lawrey 中指出,你也无法检查类型变量:

  if(type instanceof T)//编译错误


I started to learn generics today, but this is somelike weird for me:

I have a generic method:

  public<T> HashMap<String, T> getAllEntitySameType(T type) {

        System.out.println(type.getClass());
        HashMap<String, T> result = null;

        if(type instanceof Project)
        {
            System.out.println(type.toString());
            System.out.println("Yes, instance of Project;");
        }

        if(type instanceof String)
        {
            System.out.println(type.toString());
            System.out.println("Yes, instance of String;");
        }
        this.getProjects();
        return result;
    }

And i can easily determinate the class of the T type

    Project<Double> project = new Project<Double>();
    company2.getAllEntitySameType(project);
    company2.getAllEntitySameType("TestString");

The output will be:

class Project
Yes, instance of Project;
class java.lang.String
TestString
Yes, instance of String;

I thought in generics we can't use instance of. Something is not complete in my knowledge. Thanks...

解决方案

You can use instanceof to check the raw type of an object, for example Project:

if (type instanceof Project)

Or with proper generics syntax for a Project of some unknown type:

if (type instanceof Project<?>)

But you can't reify a parameterized type like Project<Double> with instanceof, due to type erasure:

if (type instanceof Project<Double>) //compile error

As Peter Lawrey pointed out, you also can't check against type variables:

if (type instanceof T) //compile error

这篇关于在泛型方法中使用instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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