Search in sources :

Example 81 with TypeLiteral

use of com.google.inject.TypeLiteral in project guice by google.

the class FactoryProviderTest method testGenericAssistedFactory.

public void testGenericAssistedFactory() {
    final TypeLiteral<GenericColoredCarFactory<Mustang>> mustangTypeLiteral = new TypeLiteral<GenericColoredCarFactory<Mustang>>() {
    };
    final TypeLiteral<GenericColoredCarFactory<Camaro>> camaroTypeLiteral = new TypeLiteral<GenericColoredCarFactory<Camaro>>() {
    };
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Double.class).toInstance(5.0d);
            bind(int.class).annotatedWith(Names.named("horsePower")).toInstance(250);
            bind(int.class).annotatedWith(Names.named("modelYear")).toInstance(1984);
            bind(mustangTypeLiteral).toProvider(FactoryProvider.newFactory(mustangTypeLiteral, TypeLiteral.get(Mustang.class)));
            bind(camaroTypeLiteral).toProvider(FactoryProvider.newFactory(camaroTypeLiteral, TypeLiteral.get(Camaro.class)));
        }
    });
    GenericColoredCarFactory<Mustang> mustangFactory = injector.getInstance(Key.get(mustangTypeLiteral));
    GenericColoredCarFactory<Camaro> camaroFactory = injector.getInstance(Key.get(camaroTypeLiteral));
    Mustang blueMustang = mustangFactory.create(Color.BLUE);
    assertEquals(Color.BLUE, blueMustang.color);
    assertEquals(5.0d, blueMustang.engineSize, 0.0);
    Camaro redCamaro = camaroFactory.create(Color.RED);
    assertEquals(Color.RED, redCamaro.color);
    assertEquals(1984, redCamaro.modelYear);
    assertEquals(250, redCamaro.horsePower);
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) AbstractModule(com.google.inject.AbstractModule)

Example 82 with TypeLiteral

use of com.google.inject.TypeLiteral in project guice by google.

the class Java8LanguageFeatureBindingTest method testBinding_lambdaToInterface.

// Some of these tests are kind of weird.
// See https://github.com/google/guice/issues/757 for more on why they exist.
public void testBinding_lambdaToInterface() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(new TypeLiteral<Predicate<Object>>() {
            }).toInstance(o -> o != null);
        }
    });
    Predicate<Object> predicate = injector.getInstance(new Key<Predicate<Object>>() {
    });
    assertTrue(predicate.test(new Object()));
    assertFalse(predicate.test(null));
}
Also used : Predicate(java.util.function.Predicate) Inject(com.google.inject.Inject) Key(com.google.inject.Key) Callable(java.util.concurrent.Callable) UUID(java.util.UUID) Injector(com.google.inject.Injector) Provider(com.google.inject.Provider) CreationException(com.google.inject.CreationException) Provides(com.google.inject.Provides) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Guice(com.google.inject.Guice) ProvisionException(com.google.inject.ProvisionException) TestCase(junit.framework.TestCase) TypeLiteral(com.google.inject.TypeLiteral) Collections(java.util.Collections) AbstractModule(com.google.inject.AbstractModule) Injector(com.google.inject.Injector) AbstractModule(com.google.inject.AbstractModule) Predicate(java.util.function.Predicate)

Example 83 with TypeLiteral

use of com.google.inject.TypeLiteral in project guice by google.

the class RealMultibinder method collectionOfJavaxProvidersOf.

@SuppressWarnings("unchecked")
static <T> TypeLiteral<Collection<javax.inject.Provider<T>>> collectionOfJavaxProvidersOf(TypeLiteral<T> elementType) {
    Type providerType = Types.newParameterizedType(javax.inject.Provider.class, elementType.getType());
    Type type = Types.collectionOf(providerType);
    return (TypeLiteral<Collection<javax.inject.Provider<T>>>) TypeLiteral.get(type);
}
Also used : Type(java.lang.reflect.Type) TypeLiteral(com.google.inject.TypeLiteral) Provider(com.google.inject.Provider)

Example 84 with TypeLiteral

use of com.google.inject.TypeLiteral in project guice by google.

the class TypeConverterBindingProcessor method convertToPrimitiveType.

private static <T> void convertToPrimitiveType(InjectorImpl injector, Class<T> primitiveType, final Class<T> wrapperType) {
    try {
        final Method parser = wrapperType.getMethod("parse" + capitalize(primitiveType.getName()), String.class);
        TypeConverter typeConverter = new TypeConverter() {

            @Override
            @SuppressWarnings("unchecked")
            public Object convert(String value, TypeLiteral<?> toType) {
                try {
                    return parser.invoke(null, value);
                } catch (IllegalAccessException e) {
                    throw new AssertionError(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getTargetException().getMessage());
                }
            }

            @Override
            public String toString() {
                return "TypeConverter<" + wrapperType.getSimpleName() + ">";
            }
        };
        convertToClass(injector, wrapperType, typeConverter);
    } catch (NoSuchMethodException e) {
        throw new AssertionError(e);
    }
}
Also used : TypeConverter(com.google.inject.spi.TypeConverter) TypeLiteral(com.google.inject.TypeLiteral) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 85 with TypeLiteral

use of com.google.inject.TypeLiteral in project guice by google.

the class ProviderMethodsModule method createProviderMethod.

private <T> ProviderMethod<T> createProviderMethod(Binder binder, Method method, Annotation annotation) {
    binder = binder.withSource(method);
    Errors errors = new Errors(method);
    // prepare the parameter providers
    InjectionPoint point = InjectionPoint.forMethod(method, typeLiteral);
    // Define T as the method's return type.
    @SuppressWarnings("unchecked") TypeLiteral<T> returnType = (TypeLiteral<T>) typeLiteral.getReturnType(method);
    Key<T> key = getKey(errors, returnType, method, method.getAnnotations());
    try {
        key = scanner.prepareMethod(binder, annotation, key, point);
    } catch (Throwable t) {
        binder.addError(t);
    }
    Class<? extends Annotation> scopeAnnotation = Annotations.findScopeAnnotation(errors, method.getAnnotations());
    for (Message message : errors.getMessages()) {
        binder.addError(message);
    }
    return ProviderMethod.create(key, method, delegate, ImmutableSet.copyOf(point.getDependencies()), scopeAnnotation, skipFastClassGeneration, annotation);
}
Also used : TypeLiteral(com.google.inject.TypeLiteral) Message(com.google.inject.spi.Message) InjectionPoint(com.google.inject.spi.InjectionPoint)

Aggregations

TypeLiteral (com.google.inject.TypeLiteral)118 AbstractModule (com.google.inject.AbstractModule)43 Injector (com.google.inject.Injector)38 Module (com.google.inject.Module)15 Map (java.util.Map)14 Key (com.google.inject.Key)12 Provider (com.google.inject.Provider)12 ParameterizedType (java.lang.reflect.ParameterizedType)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Binding (com.google.inject.Binding)10 Annotation (java.lang.annotation.Annotation)10 HashMap (java.util.HashMap)10 Set (java.util.Set)10 Binder (com.google.inject.Binder)9 InjectionPoint (com.google.inject.spi.InjectionPoint)9 Method (java.lang.reflect.Method)9 Type (java.lang.reflect.Type)9 HashSet (java.util.HashSet)9 ProvisionException (com.google.inject.ProvisionException)7 FactoryModuleBuilder (com.google.inject.assistedinject.FactoryModuleBuilder)7