依存性注入パッケージにスコープを追加しようとしています。そこで、次のようにScopeを定義すると考えました。
public interface Scope {
<T> T apply(T type);
<T> T resolve(Class<T> type);
}
次に、そのインターフェイスを実装する列挙を次のように作成します。
public enum Scopes implements Scope {
DEFAULT,
SINGLETON {
private final Map<String, Object> singletons = new HashMap<String, Object>();
@Override
public <T> T apply(T object) {
if (!singletons.containsKey(object.getClass().getName())) {
singletons.put(object.getClass().getName(), object);
System.out.println("Applied for: " + object.getClass().getName());
}
return object;
}
@Override
@SuppressWarnings("unchecked")
public <T> T resolve(Class<T> type) {
Object object = singletons.get(type.getClass().getName());
System.out.println("Resolved for: " + type.getClass().getName());
return object == null ? null : (T) object;
}
};
@Override
public <T> T apply(T object) {
return object;
}
@Override
public <T> T resolve(Class<T> type) {
return null;
}
}
ただし、次のようなコードを使用する場合:
System.out.println("Real type: " + type.getName());
T result = scope.resolve(type);
出力用に解決されたものは、何らかの奇妙な理由でjava.lang.Classになりますが、実際の型は正しく出力されます。