将限定符传递给提供者方法
我有一个自定义限定符,需要参数 – 枚举值。 枚举值包含特定于所需实例构造的信息。
如果我要添加新的枚举值,它会导致在模块中相同的样板代码,如下所示:
预选赛(JAVA):
@Documented @Qualifier @Retention(RUNTIME) public @interface Format { Type value() default SYSTEM; enum Type { UI("dd-MM-yyyy HH:mm"), UI_DATE("EEEE,\u00A0dd MMMM yyyy"), . . . private String format; public String getFormat() { return format; } Type(String formatString) { format = formatString; } } }
模块(科特林):
@Module class DateTimeModule { @Provides @Format(Format.Type.UI) fun dateTimeFormatterUI(): DateTimeFormatter { return DateTimeFormat.forPattern(Format.Type.UI.format).withLocale(DefaultConfigVariables.LOCALE) } @Provides @Format(Format.Type.UI_DATE) fun dateFormatterUI(): DateTimeFormatter { return DateTimeFormat.forPattern(Format.Type.UI_DATE.format).withLocale(DefaultConfigVariables.LOCALE) } . . . }
是否有可能以某种方式改变它,我只能添加一个新的实例枚举,它被传递给提供者方法或类似的东西?
不是通过匕首。 除非你编写了一个模块,你把它送入Dagger,它将不能以编程的方式读取你的注释,并根据这些值采取不同的动作。
实际上,虽然它弯曲了得墨忒耳法,但我会这样做:
public class DateTimeFormatterFactory { @Inject DateTimeFormatterFactory() {} public DateTimeFormatter forFormat(Format.Type type) { return DateTimeFormat .forPattern(type) .withLocale(DefaultConfigVariables.LOCALE); } }