Skip to content

Instantly share code, notes, and snippets.

@noel-yap
Created September 25, 2012 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noel-yap/3784775 to your computer and use it in GitHub Desktop.
Save noel-yap/3784775 to your computer and use it in GitHub Desktop.
Guice AssistedInject with Generics
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment