allow @Provides to return suppliers w/o qualifiers

This commit is contained in:
Adrian Cole 2012-02-05 21:54:40 -08:00
parent 2bc8e39e0a
commit edbd09b984
1 changed files with 36 additions and 8 deletions

View File

@ -149,18 +149,13 @@ public class AsyncRestClientProxy<T> implements InvocationHandler {
public Object lookupValueFromGuice(Method method) {
try {
//TODO: tidy
Type genericReturnType = method.getGenericReturnType();
try {
Annotation qualifier = Iterables.find(ImmutableList.copyOf(method.getAnnotations()), isQualifierPresent);
Binding<?> binding = injector.getExistingBinding(Key.get(genericReturnType, qualifier));
if (binding != null)
return binding.getProvider().get();
// try looking via supplier
return Supplier.class.cast(
injector.getInstance(Key.get(Types.newParameterizedType(Supplier.class, genericReturnType),
qualifier))).get();
return getInstanceOfTypeWithQualifier(genericReturnType, qualifier);
} catch (NoSuchElementException e) {
return injector.getInstance(Key.get(genericReturnType));
return getInstanceOfType(genericReturnType);
}
} catch (ProvisionException e) {
AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class);
@ -170,6 +165,39 @@ public class AsyncRestClientProxy<T> implements InvocationHandler {
}
}
// TODO: tidy
private Object getInstanceOfType(Type genericReturnType) {
// look for an existing binding
Binding<?> binding = injector.getExistingBinding(Key.get(genericReturnType));
if (binding != null)
return binding.getProvider().get();
// then, try looking via supplier
binding = injector.getExistingBinding(Key.get(Types.newParameterizedType(Supplier.class, genericReturnType)));
if (binding != null)
return Supplier.class.cast(binding.getProvider().get()).get();
// else try to create an instance
return injector.getInstance(Key.get(genericReturnType));
}
// TODO: tidy
private Object getInstanceOfTypeWithQualifier(Type genericReturnType, Annotation qualifier) {
// look for an existing binding
Binding<?> binding = injector.getExistingBinding(Key.get(genericReturnType, qualifier));
if (binding != null)
return binding.getProvider().get();
// then, try looking via supplier
binding = injector.getExistingBinding(Key.get(Types.newParameterizedType(Supplier.class, genericReturnType),
qualifier));
if (binding != null)
return Supplier.class.cast(binding.getProvider().get()).get();
// else try to create an instance
return injector.getInstance(Key.get(genericReturnType, qualifier));
}
@SuppressWarnings( { "unchecked", "rawtypes" })
private ListenableFuture<?> createListenableFutureForHttpRequestMappedToMethodAndArgs(Method method, Object[] args)
throws ExecutionException {