Skip to content

Instantly share code, notes, and snippets.

@SnuktheGreat
Last active October 16, 2015 09:38
Show Gist options
  • Select an option

  • Save SnuktheGreat/1304302bfe6df4c6f81c to your computer and use it in GitHub Desktop.

Select an option

Save SnuktheGreat/1304302bfe6df4c6f81c to your computer and use it in GitHub Desktop.
This test shows how generic type erasures work.
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