Last active
October 16, 2015 09:38
-
-
Save SnuktheGreat/1304302bfe6df4c6f81c to your computer and use it in GitHub Desktop.
This test shows how generic type erasures work.
This file contains hidden or 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
| package com.impressiveinteractive.playground; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Optional; | |
| import org.junit.Rule; | |
| import org.junit.Test; | |
| import org.junit.rules.ExpectedException; | |
| public class GenericTypeErasureTest { | |
| @Rule | |
| public ExpectedException exception = ExpectedException.none(); | |
| @Test | |
| public void testCastingToListOfDifferentType() throws Exception { | |
| ArrayList<SockPuppet> sockPuppets = new ArrayList<>(); | |
| sockPuppets.add(new SockPuppet()); | |
| sockPuppets.add(new SockPuppet()); | |
| sockPuppets.add(new SockPuppet()); | |
| Object mysteryObject = sockPuppets; | |
| killAllHumans((List<Human>) mysteryObject); // Oke | |
| } | |
| private void killAllHumans(List<Human> humans) { | |
| Optional<Human> optional = humans.stream().findFirst(); // Still oke | |
| exception.expect(ClassCastException.class); | |
| Human human = optional.get(); // Not oke | |
| } | |
| private static class SockPuppet {} | |
| private static class Human {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment