Search in sources :

Example 86 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class ElementsTest method testBindToConstructor.

public void testBindToConstructor() throws NoSuchMethodException, NoSuchFieldException {
    final Constructor<A> aConstructor = A.class.getDeclaredConstructor();
    final Constructor<B> bConstructor = B.class.getDeclaredConstructor(Object.class);
    final Field field = B.class.getDeclaredField("stage");
    checkModule(new AbstractModule() {

        protected void configure() {
            bind(A.class).toConstructor(aConstructor);
            bind(B.class).toConstructor(bConstructor, new TypeLiteral<B<Integer>>() {
            }).in(Singleton.class);
        }
    }, new FailingElementVisitor() {

        @Override
        public <T> Void visit(Binding<T> binding) {
            assertEquals(new Key<A>() {
            }, binding.getKey());
            return binding.acceptTargetVisitor(new FailingTargetVisitor<T>() {

                @Override
                public Void visit(ConstructorBinding<? extends T> constructorBinding) {
                    InjectionPoint injectionPoint = constructorBinding.getConstructor();
                    assertEquals(aConstructor, injectionPoint.getMember());
                    assertEquals(new TypeLiteral<A>() {
                    }, injectionPoint.getDeclaringType());
                    return null;
                }
            });
        }
    }, new FailingElementVisitor() {

        @Override
        public <T> Void visit(Binding<T> binding) {
            assertEquals(new Key<B>() {
            }, binding.getKey());
            binding.acceptScopingVisitor(new FailingBindingScopingVisitor() {

                @Override
                public Void visitScopeAnnotation(Class<? extends Annotation> annotation) {
                    assertEquals(Singleton.class, annotation);
                    return null;
                }
            });
            binding.acceptTargetVisitor(new FailingTargetVisitor<T>() {

                @Override
                public Void visit(ConstructorBinding<? extends T> constructorBinding) {
                    assertEquals(bConstructor, constructorBinding.getConstructor().getMember());
                    assertEquals(Key.get(Integer.class), getOnlyElement(constructorBinding.getConstructor().getDependencies()).getKey());
                    assertEquals(field, getOnlyElement(constructorBinding.getInjectableMembers()).getMember());
                    assertEquals(2, constructorBinding.getDependencies().size());
                    /*if[AOP]*/
                    assertEquals(ImmutableMap.of(), constructorBinding.getMethodInterceptors());
                    /*end[AOP]*/
                    return null;
                }
            });
            return null;
        }
    });
}
Also used : BindingAnnotation(com.google.inject.BindingAnnotation) Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Field(java.lang.reflect.Field) Singleton(com.google.inject.Singleton) Key(com.google.inject.Key)

Example 87 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class InjectorImpl method getProvidedKey.

private static <T> Key<T> getProvidedKey(Key<Provider<T>> key, Errors errors) throws ErrorsException {
    Type providerType = key.getTypeLiteral().getType();
    // If the Provider has no type parameter (raw Provider)...
    if (!(providerType instanceof ParameterizedType)) {
        throw errors.cannotInjectRawProvider().toException();
    }
    Type entryType = ((ParameterizedType) providerType).getActualTypeArguments()[0];
    // safe because T came from Key<Provider<T>>
    @SuppressWarnings("unchecked") Key<T> providedKey = (Key<T>) key.ofType(entryType);
    return providedKey;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Key(com.google.inject.Key)

Example 88 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class InjectorImpl method createUninitializedBinding.

/**
   * Creates a binding for an injectable type with the given scope. Looks for a scope on the type if
   * none is specified.
   */
<T> BindingImpl<T> createUninitializedBinding(Key<T> key, Scoping scoping, Object source, Errors errors, boolean jitBinding) throws ErrorsException {
    Class<?> rawType = key.getTypeLiteral().getRawType();
    ImplementedBy implementedBy = rawType.getAnnotation(ImplementedBy.class);
    // Don't try to inject arrays or enums annotated with @ImplementedBy.
    if (rawType.isArray() || (rawType.isEnum() && implementedBy != null)) {
        throw errors.missingImplementation(key).toException();
    }
    // Handle TypeLiteral<T> by binding the inner type
    if (rawType == TypeLiteral.class) {
        // we have to fudge the inner type as Object
        @SuppressWarnings("unchecked") BindingImpl<T> binding = (BindingImpl<T>) createTypeLiteralBinding((Key<TypeLiteral<Object>>) key, errors);
        return binding;
    }
    // Handle @ImplementedBy
    if (implementedBy != null) {
        Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors);
        return createImplementedByBinding(key, scoping, implementedBy, errors);
    }
    // Handle @ProvidedBy.
    ProvidedBy providedBy = rawType.getAnnotation(ProvidedBy.class);
    if (providedBy != null) {
        Annotations.checkForMisplacedScopeAnnotations(rawType, source, errors);
        return createProvidedByBinding(key, scoping, providedBy, errors);
    }
    return ConstructorBindingImpl.create(this, key, null, /* use default constructor */
    source, scoping, errors, jitBinding && options.jitDisabled, options.atInjectRequired);
}
Also used : ProvidedBy(com.google.inject.ProvidedBy) Key(com.google.inject.Key) ImplementedBy(com.google.inject.ImplementedBy)

Example 89 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class InjectorImpl method createJustInTimeBinding.

/**
   * Returns a new just-in-time binding created by resolving {@code key}. The strategies used to
   * create just-in-time bindings are:
   * <ol>
   *   <li>Internalizing Providers. If the requested binding is for {@code Provider<T>}, we delegate
   *     to the binding for {@code T}.
   *   <li>Converting constants.
   *   <li>ImplementedBy and ProvidedBy annotations. Only for unannotated keys.
   *   <li>The constructor of the raw type. Only for unannotated keys.
   * </ol>
   *
   * @throws com.google.inject.internal.ErrorsException if the binding cannot be created.
   */
private <T> BindingImpl<T> createJustInTimeBinding(Key<T> key, Errors errors, boolean jitDisabled, JitLimitation jitType) throws ErrorsException {
    int numErrorsBefore = errors.size();
    // Retrieve the sources before checking for blacklisting to guard against sources becoming null
    // due to a full GC happening after calling state.isBlacklisted and
    // state.getSourcesForBlacklistedKey.
    // TODO(user): Consolidate these two APIs.
    Set<Object> sources = state.getSourcesForBlacklistedKey(key);
    if (state.isBlacklisted(key)) {
        throw errors.childBindingAlreadySet(key, sources).toException();
    }
    // Handle cases where T is a Provider<?>.
    if (isProvider(key)) {
        // These casts are safe. We know T extends Provider<X> and that given Key<Provider<X>>,
        // createProviderBinding() will return BindingImpl<Provider<X>>.
        @SuppressWarnings({ "unchecked", "cast" }) BindingImpl<T> binding = (BindingImpl<T>) createProviderBinding((Key) key, errors);
        return binding;
    }
    // Handle cases where T is a MembersInjector<?>
    if (isMembersInjector(key)) {
        // These casts are safe. T extends MembersInjector<X> and that given Key<MembersInjector<X>>,
        // createMembersInjectorBinding() will return BindingImpl<MembersInjector<X>>.
        @SuppressWarnings({ "unchecked", "cast" }) BindingImpl<T> binding = (BindingImpl<T>) createMembersInjectorBinding((Key) key, errors);
        return binding;
    }
    // Try to convert a constant string binding to the requested type.
    BindingImpl<T> convertedBinding = convertConstantStringBinding(key, errors);
    if (convertedBinding != null) {
        return convertedBinding;
    }
    if (!isTypeLiteral(key) && jitDisabled && jitType != JitLimitation.NEW_OR_EXISTING_JIT) {
        throw errors.jitDisabled(key).toException();
    }
    // If the key has an annotation...
    if (key.getAnnotationType() != null) {
        // Look for a binding without annotation attributes or return null.
        if (key.hasAttributes() && !options.exactBindingAnnotationsRequired) {
            try {
                Errors ignored = new Errors();
                return getBindingOrThrow(key.withoutAttributes(), ignored, JitLimitation.NO_JIT);
            } catch (ErrorsException ignored) {
            // throw with a more appropriate message below
            }
        }
        throw errors.missingImplementation(key).toException();
    }
    Object source = key.getTypeLiteral().getRawType();
    BindingImpl<T> binding = createUninitializedBinding(key, Scoping.UNSCOPED, source, errors, true);
    errors.throwIfNewErrors(numErrorsBefore);
    initializeJitBinding(binding, errors);
    return binding;
}
Also used : InjectionPoint(com.google.inject.spi.InjectionPoint) Key(com.google.inject.Key)

Example 90 with Key

use of com.google.inject.Key in project roboguice by roboguice.

the class Errors method formatSource.

public static void formatSource(Formatter formatter, Object source, ElementSource elementSource) {
    String modules = moduleSourceString(elementSource);
    if (source instanceof Dependency) {
        Dependency<?> dependency = (Dependency<?>) source;
        InjectionPoint injectionPoint = dependency.getInjectionPoint();
        if (injectionPoint != null) {
            formatInjectionPoint(formatter, dependency, injectionPoint, elementSource);
        } else {
            formatSource(formatter, dependency.getKey(), elementSource);
        }
    } else if (source instanceof InjectionPoint) {
        formatInjectionPoint(formatter, null, (InjectionPoint) source, elementSource);
    } else if (source instanceof Class) {
        formatter.format("  at %s%s%n", StackTraceElements.forType((Class<?>) source), modules);
    } else if (source instanceof Member) {
        formatter.format("  at %s%s%n", StackTraceElements.forMember((Member) source), modules);
    } else if (source instanceof TypeLiteral) {
        formatter.format("  while locating %s%s%n", source, modules);
    } else if (source instanceof Key) {
        Key<?> key = (Key<?>) source;
        formatter.format("  while locating %s%n", convert(key, elementSource));
    } else {
        formatter.format("  at %s%s%n", source, modules);
    }
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) InjectionPoint(com.google.inject.spi.InjectionPoint) Dependency(com.google.inject.spi.Dependency) Member(java.lang.reflect.Member) Key(com.google.inject.Key)

Aggregations

Key (com.google.inject.Key)106 AbstractModule (com.google.inject.AbstractModule)55 Injector (com.google.inject.Injector)52 Binding (com.google.inject.Binding)36 Module (com.google.inject.Module)20 Provider (com.google.inject.Provider)18 Element (com.google.inject.spi.Element)16 Map (java.util.Map)16 HasDependencies (com.google.inject.spi.HasDependencies)14 InstanceBinding (com.google.inject.spi.InstanceBinding)13 List (java.util.List)13 TypeLiteral (com.google.inject.TypeLiteral)12 LinkedKeyBinding (com.google.inject.spi.LinkedKeyBinding)10 ProviderInstanceBinding (com.google.inject.spi.ProviderInstanceBinding)9 PrivateModule (com.google.inject.PrivateModule)8 DefaultBindingTargetVisitor (com.google.inject.spi.DefaultBindingTargetVisitor)8 Dependency (com.google.inject.spi.Dependency)8 ProviderKeyBinding (com.google.inject.spi.ProviderKeyBinding)8 ImmutableList (com.google.common.collect.ImmutableList)7 InjectionPoint (com.google.inject.spi.InjectionPoint)7