What is the correct way to check the type of an object for a universal object?

I got a warning message about Object Casting when compiling my code. I have no idea how to fix this with my current knowledge .... Suppose I have a common object, MyGenericObj<T>it is spreading from a non-common objectMyObj

Here is a sample code:

MyObj obj1 = new MyGenericObj<Integer>();
if (obj1 instanceof MyGenericObj) {
    //I was trying to check if it 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 let me know how to do it right?

Any help is appreciated.

+5
source share
1 answer

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

Class<T> , :

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

getTypeArg, , Integer.class .

+6

All Articles