【问题标题】:Preventing instanceof and casting in Java [duplicate]在Java中防止instanceof和casting [重复]
【发布时间】:2018-02-12 22:55:37
【问题描述】:

如果我想在方法签名不同的情况下使用不同的验证器,如何避免在这种情况下使用 instanceof 和强制转换?

代码

for(BatchValidator validator : validators) {
  try {     
    if (validator instanceof BatchErrorValidator) {
      ((BatchErrorValidator<T>) validator).validate(targets);
    } else if (validator instanceof BatchWarningValidator) {
      ((BatchWarningValidator<T>) validator).validate(targets, header);
    }
  } catch (BatchValidationException e) {
    handleImportExceptions(e, header.getSequenceId());
  }
}

【问题讨论】:

  • 你可以让它们使用相同的方法签名。
  • 什么是BatchValidator?这是接口吗?它是否提供validate() 方法的必需签名?

标签: java oop instanceof


【解决方案1】:

为什么不让BatchValidator.validate() 使用 2 个参数:目标和标题。各个实现可以决定他们需要使用哪些参数。

这样,您的调用循环只需将相同的参数传递给每个验证器,您不需要instanceof 或任何转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多