[英]How to Avoid casting when dealing inheritance with jackson
用例:对于配置 class,我需要使用翻译器 class。
我有 3 个配置类(A、B、C)和 3 个翻译类(X、Y、Z)。
A 是父配置 class 和 (B,C) 是子类。 同样,X 是父翻译器 class 和 (Y,Z) 是子类。
翻译器 Y 翻译 B,翻译器 Z 翻译 C 即(B -> Y,C -> Z)
NOW, I receive a string input (for config class) and I use jackson to deserialise it to a type of config class A. With Jackson, I have mentioned subTypes and Jackson is able to deserialise it to required subtypes B or C correctly.
A a = new ObjectMapper().readValue(inputString, A.class)
现在,我想做类似的事情:
if(a.type == 'B') Y.process((B)a) // Since translator Y was for B subClass
if(a.type == 'C') Z.process((C)c)// Since translator Z was for C subClass
有没有办法,我可以避免在这里进行类型转换。
我假设您已经像这样定义了process()
:
public class Y
{
public void process( B b ) {…}
}
你可以加
…
public void process( A b ) { process( (B) b ); }
…
但这只会将演员从顶部移到调用路径的下方,并稍微隐藏一下。
根据您的描述,无法避免演员阵容; 你需要它,一种或另一种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.