在泛型方法中使用instanceof

在泛型方法中使用instanceof

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

问题描述

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



我有一个通用方法:

  

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

  


$ b

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

  if(type instanceof Project<?>)

但是你不能参数化类型,如 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:43