0

While working today I've stumbled across a situation similar what the test class below replicates. The test in the test class takes a target object with two maps, one of generic types String and String, and the other of types Integer and Integer. Using the reflective call Field#set() I am able to set the value of one to the value of the other, even though this would never be possible with standard Map#put() method calls as they are of different generic types.

public class MapTest
{
  class Target
  {
    public Map<String, String> stringMap;
    public Map<Integer, Integer> intMap;
  }

  Target target = new Target();

  @Before
  public void setUp() throws Exception
  {
    target.stringMap = new HashMap<String, String>();
    target.stringMap.put("Key1", "Value1");

    target.intMap = new HashMap<Integer, Integer>();
    target.intMap.put(1, 2);
  }

  @Test
  public void test() throws Exception
  {
    System.out.println(target.stringMap);
    System.out.println(target.intMap);

    Target.class.getField("stringMap").set(target, target.intMap);

    System.out.println(target.stringMap);
    System.out.println(target.intMap);

    assertEquals(target.stringMap, target.intMap);
  }
}

Stdout:

{Key1=Value1}
{1=2}
{1=2}
{1=2}

Should what I have done be possible? I was expecting to get an exception of some sorts to be thrown - is is configurable to make it do so?

My assumptions are that because a Map just stores pointers to other objects elsewhere, are any defined generic types only a limitation of the developer and not of the actual execution of the code itself?

Toby Smith
  • 1,173
  • 2
  • 12
  • 19
  • 3
    Generics don't exist in runtime. – killjoy Nov 09 '18 at 14:39
  • 2
    Generics are a compile-time feature. See [type erasure](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens). – Slaw Nov 09 '18 at 14:40
  • This question has been asked many times. Answer: type erasure removes the generic type at runtime. So it doesn't know what sort of map it is. – rghome Nov 09 '18 at 14:41

0 Answers0