Created
November 8, 2011 09:58
-
-
Save kosta/1347395 to your computer and use it in GitHub Desktop.
Type erasure in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TypeErasureIsReallyWeird { | |
private static class AndNowWithGenerics<LongActually> { | |
LongActually UhOh(Object o) { | |
try { | |
@SuppressWarnings("unchecked") | |
LongActually longish = (LongActually) o; | |
System.out.println( | |
"In a generic class, casting String to Long seems ok. Long value is: " + | |
longish); | |
return longish; | |
} catch(Exception e) { | |
System.out.println( | |
"In a generic class, casting String to Long gave me an " + | |
e.getClass().getName()); | |
return null; | |
} | |
} | |
} | |
public static void main(String args[]) { | |
try { | |
Long wontwork = (Long) (Object) "foo"; | |
System.out.println( | |
"Casting String to Long seems ok. Long value is: " + | |
wontwork); | |
} catch(Exception e) { | |
System.out.println( | |
"Casting String to Long gave me an " | |
+ e.getClass().getName()); | |
} | |
try { | |
Long weirdValueForLong = (new AndNowWithGenerics<Long>()).UhOh("bar"); | |
System.out.println( | |
"And this is how you put a String in a Long: " + weirdValueForLong); | |
} catch (Exception e) { | |
System.out.println( | |
"This won't work, because the Long returned here is actually a String: " + | |
e.getClass().getName()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment