Reputation: 359
I am new to generics.
Having a Map
like
private static Map<String, Object> map;
and a method like
public <T> T getObject(final Class<T> myClass) {
return (T)map.get(myClass);
}
How to change the map declaration in order to not have to do the cast when returning from the method ?
Upvotes: 6
Views: 39329
Reputation: 294
my working generic java map
public class JsonUtils {
/** gson with disable html escaping */
public static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public static <K, V> String toJson(Map<K, V> dataMap) {
return gson.toJson(dataMap);
}
}
usage
java.util.Map<String, Object> dataMap = new java.util.HashMap<>();
dataMap.put("paymentchannel", "BALANCE");
dataMap.put("shortcode", "");
dataMap.put("transtype", "cvm");
System.out.println(JsonUtils.toJson(dataMap));
Upvotes: 0
Reputation: 9245
If you're willing to drop the static
modifier of your map, than you can do like so:
public class MyClass<T> {
private Map<String, T> map;
public T getObject(final Class<T> myClass) {
return map.get(myClass);
}
}
Otherwise:
It is a compile-time error to refer to a type parameter of a generic class C anywhere in:
- the declaration of a static member of C
(excerpt from the JLS), which prevents you from using parameterized class to achieve the above.
What you were trying to do, however, is to refer a parameterized method's type-parameter from another member (which happen to also be static), which also unreachable.
Upvotes: 0
Reputation: 3673
You would need to make a generic class, not a generic method:
public class MyClass<T> {
private Map<String, T> map;
public T getObject(final String key) {
return map.get(key);
}
}
Also, I changed the parameter from a Class to a String. It doesn't make sense to pass a Class if map.get() expects a String.
Edit: I didn't notice that map was static. If you can change it to non-static without it breaking other parts of your program, this could work. If you can't, then you cannot avoid a cast.
Upvotes: 10