有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在泛型方法中使用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, instance of Project;");
        }

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

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

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

输出将是:

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

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


共 (1) 个答案

  1. # 1 楼答案

    可以使用instanceof检查对象的原始类型,例如Project

    if (type instanceof Project)
    

    或者使用某种未知类型的Project的适当泛型语法:

    if (type instanceof Project<?>)
    

    但是你不能reifyProject<Double>这样的参数化类型加instanceof,因为type erasure

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

    正如Peter Lawrey pointed out,您也不能检查类型变量:

    if (type instanceof T) //compile error