Skip to content

Instantly share code, notes, and snippets.

@kosta
Created November 8, 2011 09:58
Show Gist options
  • Save kosta/1347395 to your computer and use it in GitHub Desktop.
Save kosta/1347395 to your computer and use it in GitHub Desktop.
Type erasure in java
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