Usage of instanceof in a generic method

为君一笑 提交于 2019-12-10 11:33:57

问题


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...


回答1:


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


来源:https://stackoverflow.com/questions/14219759/usage-of-instanceof-in-a-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!