use of com.google.inject.Key in project guice by google.
the class FactoryProvider2 method getBindingFromNewInjector.
/**
* Creates a child injector that binds the args, and returns the binding for the method's result.
*/
public Binding<?> getBindingFromNewInjector(final Method method, final Object[] args, final AssistData data) {
checkState(injector != null, "Factories.create() factories cannot be used until they're initialized by Guice.");
final Key<?> returnType = data.returnType;
// We ignore any pre-existing binding annotation.
final Key<?> returnKey = Key.get(returnType.getTypeLiteral(), RETURN_ANNOTATION);
Module assistedModule = new AbstractModule() {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected // raw keys are necessary for the args array and return value
void configure() {
Binder binder = binder().withSource(method);
int p = 0;
if (!data.optimized) {
for (Key<?> paramKey : data.paramTypes) {
// Wrap in a Provider to cover null, and to prevent Guice from injecting the parameter
binder.bind((Key) paramKey).toProvider(Providers.of(args[p++]));
}
} else {
for (Key<?> paramKey : data.paramTypes) {
// Bind to our ThreadLocalProviders.
binder.bind((Key) paramKey).toProvider(data.providers.get(p++));
}
}
Constructor constructor = data.constructor;
// message for the user.
if (constructor != null) {
binder.bind(returnKey).toConstructor(constructor, (TypeLiteral) data.implementationType).in(// make sure we erase any scope on the implementation type
Scopes.NO_SCOPE);
}
}
};
Injector forCreate = injector.createChildInjector(assistedModule);
Binding<?> binding = forCreate.getBinding(returnKey);
// If we have providers cached in data, cache the binding for future optimizations.
if (data.optimized) {
data.cachedBinding = binding;
}
return binding;
}
use of com.google.inject.Key in project guice by google.
the class FactoryProvider2 method constructorHasMatchingParams.
/**
* Matching logic for constructors annotated with AssistedInject. This returns true if and only if
* all @Assisted parameters in the constructor exactly match (in any order) all @Assisted
* parameters the method's parameter.
*/
private boolean constructorHasMatchingParams(TypeLiteral<?> type, Constructor<?> constructor, List<Key<?>> paramList, Errors errors) throws ErrorsException {
List<TypeLiteral<?>> params = type.getParameterTypes(constructor);
Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
int p = 0;
List<Key<?>> constructorKeys = Lists.newArrayList();
for (TypeLiteral<?> param : params) {
Key<?> paramKey = Annotations.getKey(param, constructor, paramAnnotations[p++], errors);
constructorKeys.add(paramKey);
}
// Require that every key exist in the constructor to match up exactly.
for (Key<?> key : paramList) {
// If it didn't exist in the constructor set, we can't use it.
if (!constructorKeys.remove(key)) {
return false;
}
}
// If any keys remain and their annotation is Assisted, we can't use it.
for (Key<?> key : constructorKeys) {
if (key.getAnnotationType() == Assisted.class) {
return false;
}
}
// All @Assisted params match up to the method's parameters.
return true;
}
use of com.google.inject.Key in project guice by google.
the class FactoryModuleBuilderTest method testFactoryBindingDependencies.
public void testFactoryBindingDependencies() {
// validate dependencies work in all stages & as a raw element,
// and that dependencies work for methods, fields, constructors,
// and for @AssistedInject constructors too.
Module module = new AbstractModule() {
@Override
protected void configure() {
bind(Integer.class).toInstance(42);
bind(Double.class).toInstance(4.2d);
bind(Float.class).toInstance(4.2f);
bind(String.class).annotatedWith(named("dog")).toInstance("dog");
bind(String.class).annotatedWith(named("cat1")).toInstance("cat1");
bind(String.class).annotatedWith(named("cat2")).toInstance("cat2");
bind(String.class).annotatedWith(named("cat3")).toInstance("cat3");
bind(String.class).annotatedWith(named("arbitrary")).toInstance("fail!");
install(new FactoryModuleBuilder().implement(Animal.class, Dog.class).build(AnimalHouse.class));
}
};
Set<Key<?>> expectedKeys = ImmutableSet.<Key<?>>of(Key.get(Integer.class), Key.get(Double.class), Key.get(Float.class), Key.get(String.class, named("dog")), Key.get(String.class, named("cat1")), Key.get(String.class, named("cat2")), Key.get(String.class, named("cat3")));
Injector injector = Guice.createInjector(module);
validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
injector = Guice.createInjector(Stage.TOOL, module);
validateDependencies(expectedKeys, injector.getBinding(AnimalHouse.class));
List<Element> elements = Elements.getElements(module);
boolean found = false;
for (Element element : elements) {
if (element instanceof Binding) {
Binding<?> binding = (Binding<?>) element;
if (binding.getKey().equals(Key.get(AnimalHouse.class))) {
found = true;
validateDependencies(expectedKeys, binding);
break;
}
}
}
assertTrue(found);
}
use of com.google.inject.Key in project guice by google.
the class FactoryProvider2Test method testGeneratedDefaultMethodsForwardCorrectly.
// See https://github.com/google/guice/issues/904
public void testGeneratedDefaultMethodsForwardCorrectly() {
final Key<AbstractAssisted.Factory<ConcreteAssisted, String>> concreteKey = new Key<AbstractAssisted.Factory<ConcreteAssisted, String>>() {
};
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(ConcreteAssistedWithOverride.Factory.class));
install(new FactoryModuleBuilder().build(ConcreteAssistedWithOverride.Factory2.class));
install(new FactoryModuleBuilder().build(ConcreteAssistedWithoutOverride.Factory.class));
install(new FactoryModuleBuilder().build(Public.Factory.class));
install(new FactoryModuleBuilder().build(concreteKey));
}
});
ConcreteAssistedWithOverride.Factory factory1 = injector.getInstance(ConcreteAssistedWithOverride.Factory.class);
factory1.create("foo");
AbstractAssisted.Factory<ConcreteAssistedWithOverride, String> factory1Abstract = factory1;
factory1Abstract.create("foo");
ConcreteAssistedWithOverride.Factory2 factory2 = injector.getInstance(ConcreteAssistedWithOverride.Factory2.class);
factory2.create("foo");
factory2.create(new StringBuilder("foo"));
AbstractAssisted.Factory<ConcreteAssistedWithOverride, String> factory2Abstract = factory2;
factory2Abstract.create("foo");
ConcreteAssistedWithoutOverride.Factory factory3 = injector.getInstance(ConcreteAssistedWithoutOverride.Factory.class);
factory3.create("foo");
AbstractAssisted.Factory<ConcreteAssistedWithoutOverride, String> factory3Abstract = factory3;
factory3Abstract.create("foo");
Public.Factory factory4 = injector.getInstance(Public.Factory.class);
factory4.create("foo");
factory4.create(new StringBuilder("foo"));
AbstractAssisted.Factory<Public, String> factory4Abstract = factory4;
factory4Abstract.create("foo");
AbstractAssisted.Factory<ConcreteAssisted, String> factory5 = injector.getInstance(concreteKey);
factory5.create("foo");
}
use of com.google.inject.Key in project guice by google.
the class ScopeRequestIntegrationTest method testNullReplacement.
public final void testNullReplacement() throws Exception {
Injector injector = Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
bindConstant().annotatedWith(Names.named(SomeObject.INVALID)).to(SHOULDNEVERBESEEN);
bind(SomeObject.class).in(RequestScoped.class);
}
});
Callable<SomeObject> callable = injector.getInstance(Caller.class);
try {
assertNotNull(callable.call());
fail();
} catch (ProvisionException pe) {
assertTrue(pe.getCause() instanceof OutOfScopeException);
}
// Validate that an actual null entry in the map results in a null injected object.
Map<Key<?>, Object> map = Maps.newHashMap();
map.put(Key.get(SomeObject.class), null);
callable = ServletScopes.scopeRequest(injector.getInstance(Caller.class), map);
assertNull(callable.call());
}
Aggregations