Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to check the object type for Generic object?

I got a warning message on Object Casting while compiling my code. I have no idea how to fix it with my current knowledge.... Let's say I have a Generic Object MyGenericObj<T> it is extends from a non-Generic Object MyObj

Here is a sample code:

MyObj obj1 = new MyGenericObj<Integer>();
if (obj1 instanceof MyGenericObj) {
    //I was trying to check if it's instance of MyGenericObj<Integer>
    //but my IDE saying this is wrong syntax.... 
    MyGenericObj<Integer> obj2 = (MyGenericObj<Integer>) obj1;
    //This line of code will cause a warning message when compiling 
}

Could you please let me know what's the proper way of doing this?

Any help is appreciated.

like image 422
user2296188 Avatar asked Apr 19 '13 16:04

user2296188


1 Answers

Because of type erasure, there is no way to do that: MyGenericObj<Integer> is actually a MyGenericObj<Object> behind the scene, regardless of its type parameter.

One way around this would be adding a Class<T> property to your generic object, like this:

class MyGenericObject<T> {
    private final Class<T> theClass;
    public Class<T> getTypeArg() {
        return theClass;
    }
    MyGenericObject(Class<T> theClass, ... the rest of constructor parameters) {
        this.theClass = theClass;
        ... the rest of the constructor ...
    }
}

Now you can use getTypeArg to find the actual class of the type parameter, compare it to Integer.class, and make a decision based on that.

like image 165
Sergey Kalinichenko Avatar answered Sep 19 '22 04:09

Sergey Kalinichenko