1

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

7
  • 4
    You can't do type instanceof T ;) Commented Jan 8, 2013 at 16:47
  • 1
    @PeterLawrey: That should be an answer, IMO, because that's the core of the OP's confusion. Commented Jan 8, 2013 at 16:52
  • so as it seems, i can not use exactly the opposite of what i've used? Commented Jan 8, 2013 at 16:52
  • You can do System.out.println(type); so you don't even know if it is null or not. Commented Jan 8, 2013 at 16:54
  • thanks, i can really use everything. So the thing is i can determine the arguments and i can't determine the parameters... Thanks! Wold you mind doing an answer? and i can accept it! Thanks! Commented Jan 8, 2013 at 17:05

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Anyway i make a mistake, because Project is a parameterized type ---> Project<Double> ... So now?:)
@czupe Edited to address that.
Thanks, now easier to understand. Voted up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.