I have wrote the following code:
public class Test
{
public static void main(String args[]) throws ParseException
{
System.out.println(new Generic<Integer>("one").type); //outputs "one"
}
}
class Generic<T>
{
public T type;
public Generic(Object obj)
{
type = (T)obj;
}
}
And i thought i will get an exception while doing the cast, but i didnt. I get the output: "one". But if i do new generic<Integer>, type become a variable of type Integer, so how can i cast the String "one" to T and store it in the variable type in my generic class without getting an exception? An explanation would be great.
There is no exception because type erasure removes any checking of the Integer type from your code. Since println takes Object the compiler doesn't need to insert a cast, and the code simply erases to:
System.out.println(new Generic("one").type);
Try the following assignment instead:
Integer i = new Generic<Integer>("one").type;
In that case you'll get a ClassCastException because the code erases to:
Integer i = (Integer)new Generic("one").type;
Notice that switching the types behaves differently. This will throw a ClassCastException:
System.out.println(new Generic<String>(123).type);
That's because the println(String) overload is used, so the code erases to:
System.out.println((String)new Generic(123).type);
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