Search in sources :

Example 6 with TypeConverter

use of com.google.inject.spi.TypeConverter in project roboguice by roboguice.

the class TypeConversionTest method testStringIsConvertedOnlyOnce.

public void testStringIsConvertedOnlyOnce() {
    final TypeConverter converter = new TypeConverter() {

        boolean converted = false;

        public Object convert(String value, TypeLiteral<?> toType) {
            if (converted) {
                throw new AssertionFailedError("converted multiple times!");
            }
            converted = true;
            return new Date();
        }
    };
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            convertToTypes(Matchers.only(TypeLiteral.get(Date.class)), converter);
            bindConstant().annotatedWith(NumericValue.class).to("unused");
        }
    });
    Date first = injector.getInstance(Key.get(Date.class, NumericValue.class));
    Date second = injector.getInstance(Key.get(Date.class, NumericValue.class));
    assertSame(first, second);
}
Also used : TypeConverter(com.google.inject.spi.TypeConverter) AssertionFailedError(junit.framework.AssertionFailedError) Date(java.util.Date)

Aggregations

TypeConverter (com.google.inject.spi.TypeConverter)6 TypeLiteral (com.google.inject.TypeLiteral)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 Date (java.util.Date)2 AssertionFailedError (junit.framework.AssertionFailedError)2