gpt4 book ai didi

java - guice:自动绑定(bind)泛型类

转载 作者:行者123 更新时间:2023-12-02 08:56:08 25 4
gpt4 key购买 nike

是否可以自动绑定(bind)泛型类?考虑一下:

通用接口(interface):

public interface IAction<T> {
T echo(T inst);
}

长子类型:

public class LongAction implements IAction<Long> {    
@Override
public Long echo(Long inst) {return inst;}
}

字符串子类型:

public class StringAction implements IAction<String> {
@Override
public String echo(String inst) {return inst;}
}

自定义模块:公共(public)类 CustomModule 扩展 AbstractModule {

@Override
protected void configure() {
//do this automagically?
bind(new TypeLiteral<IAction<String>>() {}).to(StringAction.class);
bind(new TypeLiteral<IAction<Long>>() {}).to(LongAction.class);
//
}

}

主要

// i know i can obtain the correct instance
IAction<String> is = injector.getInstance(new Key<IAction<String>>(){});

是否可以通过某种方式(例如:基本抽象类、反射或其他方式)自动绑定(bind)StringActionLongAction 类的绑定(bind)?我尝试过使用反射,但没有成功。

最佳答案

如果您不想显式列出实现,则必须执行某种类路径扫描。 Guava 有一些支持,其 ClassPath例如,类。

请注意,类路径扫描与 Guice 的设计理念有些对立。为您编写的每个实现添加一行到模块中真的需要付出如此多的额外努力吗?

关于java - guice:自动绑定(bind)泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936204/

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