gpt4 book ai didi

java - 在 Guice 中动态绑定(bind)实例

转载 作者:行者123 更新时间:2023-11-30 02:42:04 24 4
gpt4 key购买 nike

注意:尽管名称相似,但答案是 Dynamically bind instances using guice无法解决我的问题,因为我需要直接注入(inject)所有注入(inject)而不是在 map 中。

我有一组Class -> 实例对。它们存储在 Guava 的 ClassToInstanceMap 中。我想将该 ClassToInstanceMap 传递给我的自定义 Module 并遍历每个条目以执行实际的绑定(bind)。我该怎么做?

import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.inject.AbstractModule;
import com.google.inject.Module;

public class InstanceModuleBuilder {
private final ImmutableClassToInstanceMap.Builder<Object> instancesBuilder = ImmutableClassToInstanceMap.builder();
public <T> InstanceModuleBuilder bind(Class<T> type, T instance) {
instancesBuilder.put(type, instance);
return this;
}
public Module build() {
return new InstanceModule(instancesBuilder.build());
}
static class InstanceModule extends AbstractModule {
private final ImmutableClassToInstanceMap<Object> instances;
InstanceModule(ImmutableClassToInstanceMap<Object> instances) {
this.instances = instances;
}
@Override protected void configure() {
for (Class<?> type : instances.keySet()) {
bind(type).toInstance(instances.getInstance(type)); // Line with error
}
}
}
}

当我编译上面的代码时,出现以下错误:

InstanceModuleBuilder.java:[38,52] incompatible types: inference variable T has incompatible bounds
equality constraints: capture#1 of ?
upper bounds: capture#2 of ?,java.lang.Object

我还尝试了以下绑定(bind):

for (Map.Entry<? extends Object,Object> e: instances.entrySet()) {
bind(e.getKey()).toInstance(e.getValue());
}

或者

for (Map.Entry<? extends Object,Object> e: instances.entrySet()) {
bind(e.getKey()).toInstance(e.getKey().cast(e.getValue()));
}

但是没有一个可以编译。

最佳答案

我摆脱了泛型并且它起作用了:

    @Override protected void configure() {
for (Class type : instances.keySet()) {
bind(type).toInstance(instances.getInstance(type));
}
}

关于java - 在 Guice 中动态绑定(bind)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41364778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com