将东西放在Map <?,?>中或将Map <String,String>转换为Map <?,?>

Vis*_*ons 4 java generics easymock type-erasure

我不幸地处理了一个用以下内容定义的接口

public Map<?, ?> getMap(String key);
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

并且编译器是borking.

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 ?>)
Run Code Online (Sandbox Code Playgroud)

如果我尝试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>)
Run Code Online (Sandbox Code Playgroud)

如果我做pageMapsMap<?,?>,我不能把字符串放在里面.

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)
Run Code Online (Sandbox Code Playgroud)

我已经看到一些客户端代码执行丑陋的未经检查的转换,例如

@SuppressWarnings("unchecked")
        final Map<String, String> emptySearchResultsPageMaps = (Map<String, String>) conf.getMap("emptySearchResultsPage");
Run Code Online (Sandbox Code Playgroud)

如何将数据导入a Map<?,?>或将我转换Map<String,String>Map<?,?>

ass*_*ias 5

  1. 如果Map<String, String> 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);
    
    Run Code Online (Sandbox Code Playgroud)

不确定是否可以与你的嘲弄混合.这可能会奏效:

EasyMock.expect((Map<String, String>) config.getMap("sillyMap")).andReturn(pageMaps);
Run Code Online (Sandbox Code Playgroud)

另请注意,您无法使用通配符向通用集合添加任何内容.所以这:

Map<?, ?> map = ...
map.put(a, b);
Run Code Online (Sandbox Code Playgroud)

将不会编译,除非ab为null.