2
2

More than 5 years have passed since last update.

Javaにおける異種コンテナの実装(Effective Java 2ndから)

Last updated at Posted at 2012-02-14

自分のよく使う実装メモからの移植投稿

import java.util.HashMap;
import java.util.Map;

public class Test
{

    private Map<Class<?>, Object> contents = new HashMap<Class<?>, Object>();
    private <T> T getContent(Class<T> type){

        return  type.cast(contents.get(type));
    }

    public static void main(String[] args)
    {

        Test test = new Test();

        test.contents.put(String.class, "メモですよ");


        String newMemo = test.getContent(String.class);
        System.out.println(newMemo);

    }
}

異種コンテナは、インターフェースをキーにそのインスタンスを保持するようなフィールドの型として便利。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2