是否可以设计一种在编译时调用不同方法重载的方法?
可以说,我有这个小班:
@RequiredArgsConstructor
public class BaseValidator<T> {
private final T newValue;
}
现在,我需要返回不同对象的方法(取决于T)。像这样:
private StringValidator getValidator() {
return new ValidationString(newValue);
}
private IntegerValidator getValidator() {
return new Validation(newValue);
}
最后,我想要一个非常流畅的调用层次结构,看起来像这样:
new BaseValidator("string")
.getValidator() // which returns now at compile-time a StringValidator
.checkIsNotEmpty();
//or
new BaseValidator(43)
.getValidator() // which returns now a IntegerValidator
.checkIsBiggerThan(42);
在我的“真实”案例中(我有一种非常具体的方法来更新对象和每个对象的很多条件,并且复制和粘贴问题的可能性非常高。所以向导强制所有开发人员实施精确这边走。) : 理想图像
我尝试了不同的方法。验证器中的复杂泛型,或使用泛型。我的最后一个方法看起来像这样。
public <C> C getValidator() {
return (C) getValidation(newValue);
}
private ValidationString getValidation(String newValue) {
return new StringValidator(newValue);
}
private ValidationInteger getValidation(Integer newValue) {
return new IntegerValidation(newValue);
}
诀窍是什么?
//编辑:我希望它在编译时而不是instanceof在运行时使用 -checks。
慕盖茨4494581
慕田峪9158850
相关分类