5

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.

Maroun
  • 87,488
  • 26
  • 172
  • 226
user2296188
  • 139
  • 8

1 Answers1

6

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
  • First Thanks for your help. So you mean in 'theClass' object, you have a place to save the object type, then you compare that to 'Integer.class'? – user2296188 Apr 19 '13 at 17:04
  • @user2296188 Essentially, yes - you write something like this: `if (i instanceof MyGenericObject && ((MyGenericObject)i).getTypeArg() == Integer.class) {...}`. Take a look at this demo on ideone ([link](http://ideone.com/j85Uj9)) for a working example. – Sergey Kalinichenko Apr 19 '13 at 17:17
  • I got it now~~ Thank you very much!!! I will try it out and see if the warning message is cleared... – user2296188 Apr 19 '13 at 17:51