Stack Overflow Asked by Astha Srivastava on December 18, 2021
I have a method which accepts two values and converts it into key-value pair of a map and returns it to the calling method. The key is always String but the value can be of any Class. I can’t seem to convert the value into generic while accepting in method signature. Here’s my code:
private Map<String, Class<T>> mapBuilder(String key, T value) {
Map<String, Class <T>> map = new HashMap<>();
map.put(key, value);
return map;
}
Can someone tell what can be done instead?
Are you sure you want to have a map with Class
as a value? If so, you have firstly define a generic type parameter <T>
either at the class level (public class MyClass <T> { ... }
or at the method level:
private <T> Map<String, Class<T>> mapBuilder(String key, T value) {
Map<String, Class <T>> map = new HashMap<>();
map.put(key, (Class<T>) value.getClass());
return map;
}
Note the following:
Class<T>
to the map as a value, you have to get it from the T
object.getClass
returns Class<?>
, so an explicit casting is needed (also in the snippet above).Finally, I'd prefer a solution with the wildcard parameter:
private Map<String, Class<?>> mapBuilder(String key, T value) {
Map<String, Class <?>> map = new HashMap<>();
map.put(key, value.getClass());
return map;
}
Answered by Nikolas Charalambidis on December 18, 2021
The Class
is too much. T
already refers to the type:
private <T> Map<String, T> mapBuilder(String key, T value) {
Map<String, T> map = new HashMap<>();
map.put(key, value);
return map;
}
Class<T>
would refer to the class-object of T
Answered by Felix on December 18, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP