czupe
czupe

Reputation: 4919

Usage of instanceof in a generic method

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

Upvotes: 1

Views: 1003

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

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

Upvotes: 6

Related Questions