Java generic function: how to return Generic type

后端 未结 6 1965
春和景丽
春和景丽 2020-12-16 15:46

Here\'s a Java generic pattern:

public  T getResultData(Class resultClass, other_args) { 
   ...
   return resultClass.cast(T-thing);
}
         


        
6条回答
  •  孤街浪徒
    2020-12-16 16:25

    If you don't really need the exact generic type of the map and your code does not rely on that type but you're simply annoyed by the warnings you could write:

    Map returnedMap;
    returnedMap = thing.getResultData(Map.class, some_other_args);
    

    then you can use any of the map methods that are not type-parametrized like containsKey, clear, iterator and so on or iterate over the entrySet or pass returnedMap to any generic method and everything will be type safe.

    Map returnedMap;
    returnedMap = thing.getResultData(Map.class, some_other_args);
    
    Object myKey = ...;
    
    Object someValue = returnedMap.get(myKey);
    
    for (Iterator> it = returnedMap.entrySet().iterator(); it.hasNext(); )
      if (it.next().equals(myKey))
        it.remove();
    
    for (Map.Entry e : returnedMap.entrySet()) {
      if (e.getKey().equals(myKey))
        e.setValue(null); // if the map supports null values
    }
    
    doSomething(returnedMap);
    
    ...
    
     void doSomething(Map map) { ... }
    

    there is actually many things that you can do with a Map in a type-safe manner without knowing its key or value type.

提交回复
热议问题