Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在泛型方法中使用instanceof_Java_Generics_Instanceof - Fatal编程技术网

Java 在泛型方法中使用instanceof

Java 在泛型方法中使用instanceof,java,generics,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) {

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

我有一个通用方法:

  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;
    }
我认为在泛型中我们不能使用实例。据我所知,有些东西不完整。谢谢…

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

或者对于某个未知类型的项目使用适当的泛型语法:

if (type instanceof Project<?>)
作为Peter Lawrey,您也不能检查类型变量:

if (type instanceof T) //compile error
您可以使用instanceof检查对象的原始类型,例如Project:

或者对于某个未知类型的项目使用适当的泛型语法:

if (type instanceof Project<?>)
作为Peter Lawrey,您也不能检查类型变量:

if (type instanceof T) //compile error

您不能键入instanceof t@彼得拉维:我想这应该是一个答案,因为这是OP困惑的核心。所以看起来,我不能使用与我使用的完全相反的方法?你可以使用System.out.printltype;所以你甚至不知道它是否为空。谢谢,我真的可以使用所有东西。所以问题是我可以确定参数,但我不能确定参数。。。谢谢你介意回答一下吗?我可以接受!谢谢您不能键入instanceof t@彼得拉维:我想这应该是一个答案,因为这是OP困惑的核心。所以看起来,我不能使用与我使用的完全相反的方法?你可以使用System.out.printltype;所以你甚至不知道它是否为空。谢谢,我真的可以使用所有东西。所以问题是我可以确定参数,但我不能确定参数。。。谢谢你介意回答一下吗?我可以接受!谢谢无论如何,我犯了一个错误,因为项目是一个参数化类型-->项目。。。那么现在呢?:@czupe编辑了这个问题。谢谢,现在更容易理解了。投票通过了!无论如何,我犯了一个错误,因为项目是一个参数化类型-->项目。。。那么现在呢?:@czupe编辑了这个问题。谢谢,现在更容易理解了。投票通过了!
if (type instanceof Project<Double>) //compile error
if (type instanceof T) //compile error