Skip to content

Instantly share code, notes, and snippets.

@Mazyod
Created November 10, 2015 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mazyod/1a35d0170c067cda6445 to your computer and use it in GitHub Desktop.
Save Mazyod/1a35d0170c067cda6445 to your computer and use it in GitHub Desktop.
Java Generics
import java.util.HashMap;
import java.util.Map;
public class Driver {
static Map<String, Object> KeyValueStore = new HashMap<String, Object>();
public static void main(String[] args) throws Exception {
Driver.KeyValueStore.put("testInt", 5);
Driver.KeyValueStore.put("testString", "hello");
String s = getValue(String.class, "testString");
int i = getValue(Integer.class, "testInt");
System.out.printf("%s, %d", s, i);
}
public static <T> T getValue(Class<T> type, String key) throws ClassCastException {
Object value = Driver.KeyValueStore.get(key);
return type.cast(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment