23

我的问题归结为将@Assisted 与工厂的两个字符串参数一起使用。问题是因为Guice把type作为参数的识别机制,所以两个参数是一样的,我得到一个配置错误。

一些代码:

public class FilePathSolicitingDialog {

    //... some fields

    public static interface Factory {
        public FilePathSolicitingDialog make(Path existingPath,
                                             String allowedFileExtension,
                                             String dialogTitle);
    }

    @Inject
    public FilePathSolicitingDialog(EventBus eventBus,
                                    SelectPathAndSetTextListener.Factory listenerFactory,
                                    FilePathDialogView view,
                                    @Assisted Path existingPath,
                                    @Assisted String allowedFileExtension,
                                    @Assisted String dialogTitle) {
        //... typical ctor, this.thing = thing
    }

    // ... methods
}

问题在于双字符串参数。

我尝试使用单独的 @Named("as proper") 注释标记每个字符串,但这只会导致更多配置错误。从这些错误的声音来看,他们不想在工厂类上绑定注释,所以我没有尝试自定义绑定注释。

简单而嘈杂的解决方案是创建一个简单的参数类来包含这三个辅助值,然后简单地注入:

    public static class Config{
        private final Path existingPath;
        private final String allowedFileExtension;
        private final String dialogTitle;

        public Config(Path existingPath, String allowedFileExtension, String dialogTitle){
            this.existingPath = existingPath;
            this.allowedFileExtension = allowedFileExtension;
            this.dialogTitle = dialogTitle;
        }
    }

    public static interface Factory {
        public FilePathSolicitingDialogController make(Config config);
    }

    @Inject
    public FilePathSolicitingDialogController(EventBus eventBus,
                                              SelectPathAndSetTextListener.Factory listenerFactory,
                                              FilePathDialogView view,
                                              @Assisted Config config) {
        //reasonably standard ctor, some this.thing = thing
        // other this.thing = config.thing
    }
}

这很有效,而且很可能没有错误,但很吵。摆脱嵌套静态类的某种方法会很好。

谢谢你的帮助!

4

1 回答 1

39

看看这个文档(以前在这里):

使参数类型不同

工厂方法的参数类型必须是不同的。要使用相同类型的多个参数,请使用命名@Assisted注释来消除参数的歧义。名称必须应用于工厂方法的参数:

public interface PaymentFactory {
   Payment create(
       @Assisted("startDate") Date startDate,
       @Assisted("dueDate") Date dueDate,
       Money amount);
 }

...以及具体类型的构造函数参数:

public class RealPayment implements Payment {
   @Inject
   public RealPayment(
      CreditService creditService,
      AuthService authService,
      @Assisted("startDate") Date startDate,
      @Assisted("dueDate") Date dueDate,
      @Assisted Money amount) {
     ...
   }
 }
于 2014-05-08T23:51:49.687 回答