Servletをやった人はおなじみのjavax.servlet.http.HttpSessionのsetAttribute()/getAttribute()のようなモノをどうやって型安全にするかというのが今回のテーマ。 擬似的にはjava.util.Map型へのput/getだと思ってもらっていい。通常、Mapを使う際はキーの型と値の型を揃えてMapみたいにして使うわけだけども、汎用key-valueストア的な用途になるところはそうもいかなかったりする。 あるいは、O/Rマッピングを用いているような場合に汎用のオブジェクトとしてMapが使われることもある。DBのカラム名をキーに値を格納していたりするわけで、やはりMap型として扱わざるをえなかったりする。 これに対する解はいくつかあって、今回はメソッドスコープの型変数を用いる。 public class KeyValue { Map<Key