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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With