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?
Aucun commentaire:
Enregistrer un commentaire