com.github.nill14.utils.init.impl.QualifiedProvider Maven / Gradle / Ivy
package com.github.nill14.utils.init.impl;
import java.lang.annotation.Annotation;
import java.util.Optional;
import javax.inject.Provider;
import com.github.nill14.utils.init.api.BindingKey;
import com.github.nill14.utils.init.api.IParameterType;
import com.github.nill14.utils.init.api.IPropertyResolver;
import com.github.nill14.utils.init.api.IQualifiedProvider;
import com.google.common.reflect.TypeToken;
@SuppressWarnings("unchecked")
public class QualifiedProvider implements IQualifiedProvider {
private final IPropertyResolver resolver;
private final TypeToken typeToken;
public QualifiedProvider(TypeToken typeToken, IPropertyResolver resolver) {
this.typeToken = typeToken;
this.resolver = resolver;
}
private T resolveOrThrow(IParameterType type) {
T object = (T) resolver.resolve(type);
if (object != null) {
return object;
} else {
throw new RuntimeException("Cannot resolve " + type.getQualifier());
}
}
private Optional resolveOptional(IParameterType type) {
return Optional.ofNullable((T) resolver.resolve(type));
}
@Override
public T getNamed(String named) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, named));
return resolveOrThrow(type);
}
@Override
public Optional getOptionalNamed(String named) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, named));
return resolveOptional(type);
}
@Override
public T getQualified(Class extends Annotation> annotationType) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, annotationType));
return resolveOrThrow(type);
}
@Override
public Optional getOptionalQualified(Class extends Annotation> annotationType) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, annotationType));
return resolveOptional(type);
}
@Override
public T getQualified(Annotation annotation) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, annotation));
return resolveOrThrow(type);
}
@Override
public Optional getOptionalQualified(Annotation annotation) {
IParameterType type = IParameterType.of(BindingKey.of(typeToken, annotation));
return resolveOptional(type);
}
private final Provider> provider = new Provider>() {
@Override
public QualifiedProvider get() {
return QualifiedProvider.this;
}
};
public Provider> toProvider() {
return provider;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy