我正在编写一个流畅的 API 来验证 Map 中的 key:value
对。我有 validator 类型的层次结构。我引用了Fluent API with inheritance and generics的一个答案.
public interface IValidator {
IValidator assertValue(String key, String expectedValue) throws Exception;
abstract class Abstract implements IValidator {
protected final Map<String, String> resultMap = new HashMap<>();
@Override
public <T extends IValidator> T assertValue(String key, String expectedValue) throws Exception {
...
return (T) this;
}
}
第二级抽象子类重新定义父类型,如下所示。
public abstract class AbstractValidator
extends IValidator.Abstract {
// other logic not related to assertion
}
具体子类类似地重新定义父类型。
public class ExampleValidator
extends AbstractValidator
{
public ExampleValidator assertPromptId(String expectedValue) throws Exception{
assertValue(PROMPT_ID, expectedValue);
return this;
}
public ExampleValidator assertNameSpace(String expectedValue ) throws Exception{
assertValue(NAMESPACE, expectedValue);
return this;
}
@Override
public ExampleValidator assertValue(String key, String expectedVlaue) throws Exception {
super.assertValue(key, expectedVlaue);
return this;
}
现在,我的测试用例如下。我的问题是 .withValidator(Ivalidator validator)
无法找到 assertPromptId()
和 assertNameSpace()
的方法,但只能找到 assertValue ()
。那么如何解决呢?
public class AssertionContext {
public <T extends IValidator> T withValidator(IValidator validator) throws Exception {
return (T) validator;
}
}
// test method in main
public void invocationTest() throws Throwable {
AssertionContext verify = new AssertionContext();
verify.withValidator(new ExampleValidator()).assertNameSpace("...");
}
最佳答案
其实我发现解决办法很简单。
public <T extends IValidator> T withValidator(T t) throws Exception {
...
return t;
}
关于java - 具有 validator 继承的流畅 API - 输入 validator 实例似乎被识别为父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45068602/