简短回答:绑定到Object实例的bind()方法应该与类< Object>参数一起提供。 这就是说:Guice - 如何绑定程序运行时确定的类型?
Class<?> type = got_a_type(); Object object = got_an_object();
// Illegal - compilation error because of type check comparing ? to Object
bind(type).toInstance(object);
// Legal and working
bind((Class<Object>)type).toInstance(object);
很长的故事:
我在下面的格式从旧系统中的JSON配置文件:
{
"$type": "test_config.DummyParams",
"$object": {
"stringParam": "This is a string",
"integerParam": 1234,
"booleanParam": false
}
}
的test_config.DummyParams程序中是可用的类运行时,看起来像这样:
package test_config;
public class DummyParams {
public String stringParam;
public int integerParam;
public boolean booleanParam;
}
There的一些类,我想通过其为具有构造函数的参数吉斯创建(需要注入)DummyParams类型:
@Inject
public class DummyService(DummyParams params) { ... }
现在,由于DummyParams类是仅在运行时提供的东西(通过JSON配置文件),不能在编译的时候知道我不能使用这种类型的吉斯绑定:
// Can't do this because DummyParams type should come from config file
Object object = ...; // Getting object somehow
bind(DummyParams.class).toInstance((DummyParams)object);
我有一些旧的代码,这使我对读取类和对象(类和实例)的所有json配置文件:
class ConfigObject {
Class<?> type;
Object instance;
}
我试图简单地将它们绑定:
ConfigObject obj = config.read(); // Getting pairs from config files walker
bind(obj.type).toInstance(obj.instance);
但是,这并不编译:“Java的:在com.google.inject.binder.LinkedBindingBuilder toInstance(?捕获#189)不能被应用到(java.lang.Object中)”。
所以,这里有一个问题:如何绑定在运行时确定的类型的实例?我打破IoC的概念,并且正在做我想做的事情吗?