我正在尝试迁移一个小项目,用Guice替换一些工厂(这是我的第一个Guice试验).但是,在尝试注射仿制药时,我陷入困境.我设法提取了一个带有两个类和一个模块的小玩具示例:
import com.google.inject.Inject;
public class Console<T> {
private final StringOutput<T> out;
@Inject
public Console(StringOutput<T> out) {
this.out = out;
}
public void print(T t) {
System.out.println(out.converter(t));
}
}
public class StringOutput<T> {
public String converter(T t) {
return t.toString();
}
}
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(StringOutput.class);
bind(Console.class);
}
public static void main(String[] args) {
Injector injector = Guice.createInjector( new MyModule() );
StringOutput<Integer> out = injector.getInstance(StringOutput.class); …
Run Code Online (Sandbox Code Playgroud) 我听说过" @ImplementedBy是邪恶的",理由是它打破了DI概念并让界面意识到它的实现者.
在某些情况下可能会出现这种情况,但我经常发现它只会导致更清晰的代码(没有很长的模块可以维护),而不会真正伤害过程中的任何内容.
作为语用学,而不是纯粹主义者,你认为什么时候使用@ImplementedBy是值得的?
GSON的 toJson 函数采用类型参数,该参数在反映对象时检查类型。这对于将对象反射到集合中非常有用。
然而,我能找到的获取类型的唯一方法是通过一组丑陋的编码扭曲:
//used for reflection only
@SuppressWarnings("unused")
private static final List<MyObject> EMPTY_MY_OBJECT = null;
private static final Type MY_OBJECT_TYPE;
static {
try {
MY_OBJECT_TYPE = MyClass.class.getDeclaredField("EMPTY_MY_OBJECT").getGenericType();
} catch (Exception e) {
...
}
}
private List<MyObject> readFromDisk() {
try {
String string = FileUtils.readFileToString(new File(JSON_FILE_NAME), null);
return new Gson().fromJson(string, MY_OBJECT_TYPE);
} catch (Exception e) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以在不引用内部类变量的情况下初始化类型?伪代码看起来像这样:
private static final Type MY_OBJECT_TYPE = TypeUtils.generate(List.class, MyObject.class);
Run Code Online (Sandbox Code Playgroud) 我看过这篇关于注册泛型类型的帖子.
如何注册的例子:
bind(new TypeLiteral<Dal<RoutingResponse>>() {}).to((Class<? extends Dal<RoutingResponse>>) ResponseDal.class);
Run Code Online (Sandbox Code Playgroud)
但是如何从进样器中获取泛型类型的实例?
我试过了:
injector.getInstance(Dal<RoutingResponse>().getClass());
Run Code Online (Sandbox Code Playgroud)
但有编译错误.
我该怎么写呢?