【发布时间】:2023-03-20 14:38:02
【问题描述】:
如果我们有几个类看起来像:
@Device()
@Model("some model")
@Variant("A")
public class SomeModelVariantA extends BaseDevice {
public SomeModelVariantA (InputStream in, OutputStream out, int encoding) throws IOException {
super(in, out, encoding);
}
@Override
@CommandSpec("41")
@WithoutArguments
@WithoutResponse
public Response init(Command args) throws NotSupportedException, IOException {
return null;
}
我使用 JavaPoet 和注释处理生成类实现。
我有我使用的所有注释的项目,具有注释处理器的项目编译器来处理带注释的类和带有注释、生成的类和其他逻辑的应用程序项目。所有生成的类都扩展了基础BaseDevice 类,如下所示:
/**
* Generated on Fri Aug 28 11:03:21 EEST 2015
*/
public final class SomeModelVariantA extends BaseDevice {
public SomeModelVariantA (InputStream arg0, OutputStream arg1, int arg2) throws IOException {
super(arg0, arg1, arg2);
}
@Override
public Response init(Command arg0) throws NotSupportedException, IOException {
StringBuilder builder = new StringBuilder("");
Response response = new Response();
customCommand(41, builder.toString());
return response;
}
我已经生成了几个具体的设备,下一步是创建一个使用这些设备的 api。
public class Api {
BaseDevice device;
Api(String device, InputStream is, OutputStream os, int encoding) {
if ("SomeModelVariandA1".contentEquals(device)) {
device = new SomeModelVariantA(is, os, encoding);
}
... else if for other devices
}
public void callInit() {
device.init(null);
}
}
那么我如何为所有设备生成工厂并通过一些字符串名称将设备注入 Api 类。如何处理提供使用 api 构造函数的输入和输出流创建的设备。 dagger 2 和 google auto factory 是否适合此目的,有人可以提供示例用法吗?
谢谢
【问题讨论】:
标签: java dependency-injection dagger-2