Using instanceof in a generic method

Today I started to study generics, but for me this is something strange:

I have a general 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 define a class like T

    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 that in generics we cannot use an instance. Something is not fully known to me. Thank...

+1
source share
1 answer

You can use instanceofto check the source type of an object, for example Project:

if (type instanceof Project)

Or with the correct generic syntax for Projectan unknown type:

if (type instanceof Project<?>)

But you cannot reify the parameterized type type Project<Double>c instanceof, due to the type of erasure :

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

Peter Lawrey , :

if (type instanceof T) //compile error
+6

Source: https://habr.com/ru/post/1676053/


All Articles