Java generics with unbounded wildcard?

后端 未结 3 1596
孤城傲影
孤城傲影 2021-01-03 13:24

I have an interface to convert object to string:

public interface Converter {
    String asString(T object);
}

And a map to store

3条回答
  •  我在风中等你
    2021-01-03 13:58

    You are facing issue called wildcard capture. Java is unable to identify the type that will be received from the List data. Try refactoring your code in any of the two ways

    Method 1: Change your interface as below

    interface Converter {
        String asString(Object object);
    }
    

    Method 2: Helper method to capture wild card by type inference

    Create an helper method as below,

    // Helper method created so that the wildcard can be captured
    // through type inference.
    private  void helper(List data) {
        Map, Converter> converterMap = null;
        List stringData = null;
    
        for (T datum : data) {
            stringData.add(converterMap.get(datum.getClass()).asString(datum));
        }
    }
    

    Call this helper method as below

    List data = fetchData();
    helper(data);
    

提交回复
热议问题