我有一个工厂,它在程序运行时读取配置文件并从源代码生成一个类。
如何将新生成的类传递给 Guice 并让它从中创建一个实例。在将普通 AbstractModule 传递给 Guice 时,该类是未知的。
想法?解决方案?
编辑:问题是小部件的实现是动态编译的(如果文件发生变化,总是新鲜的),并且必须通过 Guice 自动提供。AbstractModule 示例如下所示:
public class MyModule extends AbstractModule {
protected void configure() {
bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
... more bindings
}
@Provider
public Widget provideWidget(){
Class<Widget> clazz = ModuleCompiler.compile("src/WidgetImpl.java");
// Clazz is a widget. But we do not know the exact constructors
// We need to now produce a fully injected Instance as-if it was bound
// like in a "bind(Widget.class).to(clazz)" statement
// in the configure() method
return (fully created injected class)
}
}
完整答案:
好吧......塔维安确实展示了一种方式。如果在配置模块中(通过注入)获得了 Injector,这将起作用,它将能够像这样注入新创建的类:
class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(Config.class).toInstance(Config.getInstance());
}
@Provides
public Widget provideWidget(Injector injector) throws Exception {
Class<Widget> c = ModuleCompiler.compile("src/WidgetImpl.java");
return injector.getInstance(c);
}
}
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
Widget w = injector.getInstance(Widget.class);