public final class RequestScoped<T> implements Supplier<T> {
private static ThreadLocal<Map<Class<?>, Object>> instances = new ThreadLocal<>();
private final Supplier<T> delegate;
private final Class<T> clazz;
private RequestScoped(Supplier<T> delegate, Class<T> clazz) {
this.delegate = delegate;
this.clazz = clazz;
}
public static <T> RequestScoped<T> of(Supplier<T> delegate, Class<T> clazz) {
return new RequestScoped<>(delegate, clazz);
}
@Override
public T get() {
if (instances.get() == null) {
throw new RequestScopeNotActiveException();
}
return clazz.cast(instances.get().computeIfAbsent(clazz, clazz -> delegate.get()));
}
}