在一般方法中使用instanceof

czu*_*upe 1 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;
    }
Run Code Online (Sandbox Code Playgroud)

我可以轻松确定T类的类

    Project<Double> project = new Project<Double>();
    company2.getAllEntitySameType(project);
    company2.getAllEntitySameType("TestString");
Run Code Online (Sandbox Code Playgroud)

输出将是:

class Project
Yes, instance of Project;
class java.lang.String
TestString
Yes, instance of String;
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*ora 6

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

if (type instanceof Project)
Run Code Online (Sandbox Code Playgroud)

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

if (type instanceof Project<?>)
Run Code Online (Sandbox Code Playgroud)

但你不能具体化的参数化类型一样Project<Double>instanceof,因为类型擦除:

if (type instanceof Project<Double>) //compile error
Run Code Online (Sandbox Code Playgroud)

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

if (type instanceof T) //compile error
Run Code Online (Sandbox Code Playgroud)