Skip to content

Instantly share code, notes, and snippets.

@jvz
Created December 26, 2013 23:10
Show Gist options
  • Save jvz/8140013 to your computer and use it in GitHub Desktop.
Save jvz/8140013 to your computer and use it in GitHub Desktop.
More abuse of Java generics.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class CastTest {
public static class AutoCast {
@SuppressWarnings("unchecked")
public static <T> T cast(final Object object) {
return (T) object;
}
}
@Test
public void testCast()
throws Exception {
final String s = "test";
final Object o = s;
final String t = AutoCast.cast(o);
assert t.equals(s);
}
@Test(expected = ClassCastException.class)
public void testBadCast()
throws Exception {
final Object o = new Object();
final String p = AutoCast.cast(o);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment