Created
July 25, 2013 04:01
-
-
Save Nkzn/6076815 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* http://ameblo.jp/itrice/entry-11579504554.html へのコメント用 | |
*/ | |
public class Sample { | |
public static void main(String[] args) { | |
// こんなクラスがあったとして | |
Favorites map = new Favorites(); | |
Integer i = 123; | |
map.nomalPut(Integer.class, i); | |
System.out.println(map.getObject(Integer.class)); | |
// こんな呼び出しをしたら | |
// 123 | |
// と出力されるのは容易に想像つきます。 | |
Map<String, Integer> integerMap = new HashMap<String, Integer>(); | |
integerMap.put("key", 456); | |
map.nomalPut(Map.class, integerMap); | |
integerMap = map.getObject(Map.class); | |
System.out.println(integerMap.get("key")); | |
// これは | |
// 456 | |
// と出力されるのも容易に想像がつく | |
Map<String, String> stringMap = new HashMap<String, String>(); | |
stringMap.put("key", "Mt.Fuji"); | |
map.nomalPut(Map.class, stringMap); | |
integerMap = map.getObject(Map.class);// ジェネリクスの型パラメータが違うオブジェクトget | |
Integer key = integerMap.get("key"); | |
System.out.println(key); | |
// これはどうなるかというと | |
// Mt.Fuji | |
System.out.println(key + key); // <- ClassCastException | |
} | |
public static class Favorites { | |
private Map<Class<?>, Object> map = new HashMap<Class<?>, Object>(); | |
public <T> void nomalPut(Class<T> type, T instance) { | |
map.put(type, instance); | |
} | |
public <T> T getObject(Class<T> type) { | |
return type.cast(map.get(type)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment