gpt4 book ai didi

java - Guice 可以从类文字实例化我的类吗?

转载 作者:行者123 更新时间:2023-12-01 18:32:19 25 4
gpt4 key购买 nike

我正在使用 Guice 来构建我的应用程序,但我遇到了一个特殊的情况。我有一个属性文件,其中包含我的接口(interface)和实现类的映射,例如 -

接口(interface)=Impl类

我想将interface.class绑定(bind)到我的implclass.class

这样当我请求injector.getInstance(MyInterface.class)时,Guice可以返回我的Impl类的一个实例。

这可能吗?

最佳答案

你可以做一些非常简单的事情,如下所示:

class Module extends AbstractModule {

Properties properties;

Module(Properties properties) {
this.properties = properties;
}

@Override
protected void configure() {
for (Entry<Object, Object> entry: properties.entrySet()) {
try {
Class<?> abstractClass = Class.forName((String)entry.getKey());
Class implementation = Class.forName((String)entry.getValue());
bind(abstractClass).to(implementation);
} catch (ClassNotFoundException e) {
//Handle e
}
}
}
}

请注意,属性文件需要包含完全限定的类名才能正常工作。我注意到你的问题使用短类名。看看this question添加对此的支持。

Spring 对基于 XML 的配置有广泛的支持,这可能是一个更好的选择,具体取决于您想要做什么。将绑定(bind)保留在代码中很好,因为它们可以在重构后幸存下来。

如果您试图允许客户端向您的应用程序添加功能 SPI可能是一个更好的选择。

关于java - Guice 可以从类文字实例化我的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23620469/

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