Skip to content

Instantly share code, notes, and snippets.

@gelin
Created February 20, 2020 15:35
Show Gist options
  • Save gelin/ae4bdc07609071b6edfbf57be4fd424e to your computer and use it in GitHub Desktop.
Save gelin/ae4bdc07609071b6edfbf57be4fd424e to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
public class IocKeySample {
public static class Key<T> {
private final String key;
private Key(String key) {
this.key = key;
}
private Key(Class<T> clazz, String key) {
this(key);
}
public String getKey() {
return this.key;
}
}
public static class MakeKey {
public static <T> Key<T> from(String key) {
return new Key<T>(key);
}
public static <T> Key<T> from(Class<T> clazz, String key) {
return new Key<T>(clazz, key);
}
}
public static class IOC {
static final Map<String, Object> container = new HashMap<String, Object>();
static {
container.put("integer", 42);
container.put("string", "42");
}
public static <T> T resolve(Key<T> key, Object... params) {
return (T) container.get(key.getKey()); // compilation warning: Unchecked cast: 'java.lang.Object' to 'T'
}
}
public static void main(String[] args) {
// requires explicit casting
Integer i1 = (Integer) IOC.resolve(MakeKey.from("integer"));
String s1 = (String) IOC.resolve(MakeKey.from("string"));
// implicit casting
Integer i2 = IOC.resolve(MakeKey.from(Integer.class, "integer"));
String s2 = IOC.resolve(MakeKey.from(String.class, "string"));
// wrong casting
Integer i3 = IOC.resolve(MakeKey.from(String.class, "integer"));
// compilation error: incompatible types: java.lang.String cannot be converted to java.lang.Integer
String s3 = IOC.resolve(MakeKey.from(Integer.class, "string"));
// compilation error: incompatible types: java.lang.Integer cannot be converted to java.lang.String
// wrong key type
Integer i4 = IOC.resolve(MakeKey.from(Integer.class, "string"));
// runtime exception: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
String s4 = IOC.resolve(MakeKey.from(String.class, "integer"));
// runtime exception: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
// However, this implementation doesn't stores and checks the T of the key,
// addition of such check may avoid ClassCastException on caller side.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment