java - 在泛型方法中使用 instanceof

标签 java generics 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;

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

最佳答案

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

if (type instanceof Project)

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

if (type instanceof Project<?>)

但你不能reify参数化类型,如 Project<Double>instanceof , 由于 type erasure :

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

作为彼得·劳瑞 pointed out ,你也不能检查类型变量:

if (type instanceof T) //compile error

关于java - 在泛型方法中使用 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14219759/

相关文章:

Java CookieManager 或 CookieHandler 过期了吗?

java - 确保对象实现 Comparable

java - 多态性和混淆实例

java - 从数组列表中删除元素的最有效方法?

java - 如何使用 BOM 编码/解码 UTF-16LE 字节数组?

JAVA:类型参数隐藏类类型

generics - 在 Dart 中,如何引用包含泛型参数的 Type

backbone.js: 'instanceof' 的右侧不是对象

javascript - 将 __proto__ 设置为 null,然后重新设置它会破坏 Javascript 中的 instanceof

java - 使用iText从pdf文件中提取一页