【问题标题】:Putting stuff in Map<?,?> or converting Map<String,String> to Map<?,?>将东西放入 Map<?,?> 或将 Map<String,String> 转换为 Map<?,?>
【发布时间】:2013-02-24 10:08:42
【问题描述】:

我不满意使用以下定义的接口

public Map<?, ?> getMap(String key);

我正在尝试编写使用此接口的单元测试。

Map<String,String> pageMaps = new HashMap<String,String();
pageMaps.put(EmptyResultsHandler.PAGEIDENT,"boogie");
pageMaps.put(EmptyResultsHandler.BROWSEPARENTNODEID, "Chompie");
Map<?,?> stupid = (Map<?, ?>)pageMaps;
EasyMock.expect(config.getMap("sillyMap")).andReturn(stupid);

并且编译器正在运行。

The method andReturn(Map<capture#5-of ?,capture#6-of ?>) in the type IExpectationSetters<Map<capture#5-of ?,capture#6-of ?>> is not applicable for the arguments (Map<capture#7-of ?,capture#8-of ?>)

如果我尝试直接使用pageMaps,它会告诉我:

The method andReturn(Map<capture#5-of ?,capture#6-of ?>) in the type IExpectationSetters<Map<capture#5-of ?,capture#6-of ?>> is not applicable for the arguments (Map<String,String>)

如果我将pageMaps 设为Map&lt;?,?&gt;,我就无法将字符串放入其中。

The method put(capture#3-of ?, capture#4-of ?) in the type Map<capture#3-of ?,capture#4-of ?> is not applicable for the arguments (String, String)

我见过一些客户端代码会进行丑陋的未经检查的转换,例如

@SuppressWarnings("unchecked")
        final Map<String, String> emptySearchResultsPageMaps = (Map<String, String>) conf.getMap("emptySearchResultsPage");

如何将数据导入Map&lt;?,?&gt;,或将我的Map&lt;String,String&gt; 转换为Map&lt;?,?&gt;

【问题讨论】:

  • 这里有点混乱:你试图让编译器相信愚蠢的是一个带有 2 个类型参数的 Map 你不关心,但是你仍然使用映射类型为 Map。但是您应该做的是测试该接口是否适用于您需要的任何类型组合。
  • 如果你让它返回pageMaps会发生什么? EasyMock.expect(config.getMap("sillyMap")).andReturn(pageMaps);
  • 我只关心它作为这个测试的 Map ,但这无关紧要。如果我无法将数据输入其中,我看不出如何“测试该接口是否适用于我需要的任何类型组合”。如果我使地图完全通用, put() 拒绝工作。
  • @JBNizet 这就是我所说的“当我真正使用 pageMaps 时”

标签: java generics easymock type-erasure


【解决方案1】:
  1. 没有演员表,你无法写出Map&lt;String, String&gt; map = getMap("abc");
  2. 这个问题更多地与easymock和expectandReturn方法返回/预期的类型有关,我不熟悉。你可以写

    Map<String, String> expected = new HashMap<String, String> ();
    Map<?, ?> actual = getMap("someKey");
    boolean ok = actual.equals(pageMaps);
    //or in a junit like syntax
    assertEquals(expected, actual);
    

不确定这是否可以与您的嘲笑内容混在一起。这可能会起作用:

EasyMock.expect((Map<String, String>) config.getMap("sillyMap")).andReturn(pageMaps);

另请注意,您不能使用通配符向通用集合中添加任何内容。所以这个:

Map<?, ?> map = ...
map.put(a, b);

不会编译,除非 ab 为空。

【讨论】:

  • 干得好,我没想过尝试在 expect 调用中进行投射。
猜你喜欢
  • 2016-07-29
  • 2013-05-24
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 2015-11-21
  • 2015-01-14
相关资源
最近更新 更多