gpt4 book ai didi

java - 如何编写通用的 Guice 绑定(bind)函数?

转载 作者:行者123 更新时间:2023-12-04 06:03:25 27 4
gpt4 key购买 nike

如何在下面的 Guice 绑定(bind)代码中抽象选项类型,用通用参数替换 Option ?

ArrayList<Class<? extends Option>> options = 
new ArrayList<Class<? extends Option>>();
bindMultibinder(annotation, options);

public Key<Set<Option>> bindMultibinder(
Named annotation, ArrayList<Class<? extends Option>> contents) {
Multibinder<Option> options =
Multibinder.newSetBinder(binder(), Option.class, annotation);
for (Class<? extends Option> option : contents) {
options.addBinding().to(option);
}
final Key<Set<Option>> multibinderKey =
Key.get(new TypeLiteral<Set<Option>>(){}, annotation);
return multibinderKey;
}

最佳答案

感谢 Stuart McCulloch在 Google 网上论坛上回答:

^ the new TypeLiteral<...>(){} anonymous class trick only works when the type parameter is known at compile time.

If you need to build generic types at runtime you can use the com.google.inject.util.Types utility class, for example:


final Key<Set<T>> multibinderKey =
Key.get( Types.setOf( superClass ), annotation );

为了使其正确构建,我对其进行了如下修改:
final Key<?> multibinderKey = Key.get(Types.setOf( superClass ), annotation);

所以完整的通用方法是:
public <T> Key<?> bindMultibinder(
Named annotation, Class<T> superClass, ArrayList<Class<? extends T>> contents) {
Multibinder<T> options =
Multibinder.newSetBinder(binder(), superClass, annotation);
for (Class<? extends T> t : contents) {
options.addBinding().to(t);
}
final Key<?> multibinderKey = Key.get(Types.setOf( superClass ), annotation);
return multibinderKey;
}

关于java - 如何编写通用的 Guice 绑定(bind)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8672431/

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