public
Last active

Guice AssistedInject with Generics

  • Download Gist
GuiceExploratoryTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import org.junit.Test;
 
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
 
public class GuiceExploratoryTest {
private static final String VALUE_ASSISTED_NAME = "value";
 
@Test
public void instantiateFactory() {
Injector injector = Guice.createInjector(new Module());
 
AoeuFactory aoeuFactory = injector.getInstance(Key.get(new TypeLiteral<AoeuFactory<String>>() {}));
AoeuInterface<String> aoeu = aoeuFactory.create("aoeu");
 
assertThat(aoeu.getValue(), is("aoeu"));
}
 
public static class Module extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(
new TypeLiteral<AoeuInterface<String>>() {},
new TypeLiteral<AoeuClass<String>>() {})
.build(new TypeLiteral<AoeuFactory<String>>() {}));
}
}
 
public static interface AoeuInterface<T> {
public T getValue();
}
 
public static class AoeuClass<T> implements AoeuInterface<T> {
private final T value;
 
@Inject
public AoeuClass(@Assisted(VALUE_ASSISTED_NAME) final T value) {
this.value = value;
}
 
public T getValue() {
return value;
}
}
 
public static interface AoeuFactory<T> {
public AoeuInterface<T> create(
@Assisted(VALUE_ASSISTED_NAME) final String string);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.