我正在尝试将 a 绑定Class<? extends SuperClass>
到SubClass.class
,但我找不到任何合适的东西。
实际上我的绑定需要在 a 中Set<Class<? extends SuperClass>>
,所以我已经测试了普通绑定和多重绑定,但是我不能让它们中的任何一个正常工作。我想我正确地遵循了这个问题:Using Guice, how can I injection a bounded-wildcard class? 但我不太确定,因为我的测试没有通过。
import static java.util.Collections.*;
import static org.junit.Assert.*;
import java.util.Set;
import org.junit.Test;
import com.google.inject.*;
import com.google.inject.multibindings.Multibinder;
public class GuiceWildcardTest {
@Test public void binderShouldBindClassWithWildcard() {
Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(new TypeLiteral<Class<? extends SuperClass>>() {}).toInstance(SubClass.class);
ClassHolder holder = new ClassHolder();
requestInjection(holder);
assertEquals(SubClass.class, holder.type);
}
});
}
@Test public void multibinderShouldBindSetOfClassesWithWildcard() {
Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
Multibinder.newSetBinder(binder(), new TypeLiteral<Class<? extends SuperClass>>() {}).addBinding().toInstance(SubClass.class);
SetHolder holder = new SetHolder();
requestInjection(holder);
assertEquals(singleton(SubClass.class), holder.types);
}
});
}
static class SuperClass {}
static class SubClass extends SuperClass {}
static class ClassHolder {
@Inject Class<? extends SuperClass> type;
}
static class SetHolder {
@Inject Set<Class<? extends SuperClass>> types;
}
}