简体   繁体   English

Java类继承重写列表字段

[英]Java class inheritance override List field

I am facing a problem, I have a avro generated class A and another B defined like this : 我面临一个问题,我有一个avro生成的类A和另一个B定义如下:

class A {
    String code;
}

class B {
     String someString;
     List<A> codes;
}

And custom classes that extends the two generated classes, described before, like these : 自定义类扩展了前面描述的两个生成的类,如下所示:

class CustomA extends A {
    String type;
}

class CustomB extends B {
    List<CustomA> codes;
}

It works if I remove the List<> but I realy need it. 如果我删除List <>却可以,但是我确实需要它。 For the getters/setters, I use lombok @Data annotations. 对于getter / setter,我使用lombok @Data批注。

Do somebody have a solution to work around? 有人有解决方案吗?

I suppose that the same problème will arrived with a Map<> , so I need a solution too. 我想Map <>也会出现同样的问题,所以我也需要一个解决方案。

Thanks for your answers. 感谢您的回答。

[EDIT] So I will give more concrete examples with these two screenshot below. [编辑]因此,我将在下面的两个屏幕截图中给出更具体的示例。

Here my classes declarations . 这是我的班级声明 As I said before, classes A and B (here User and ToDoItem) are generated classes by an avro schema, so I cannot modify/write in it. 如前所述,类A和B(此处为User和ToDoItem)是通过avro模式生成的类,因此无法对其进行修改/写入。 Here the compilation errors I have . 在这里,我有编译错误

You can use generics. 您可以使用泛型。 Like 喜欢

class B<T extends A> {
   List<T> codes;
}

class CustomB extends B<CustomA> {
    ...
}

The only way to make that work is generics, as @kiv_apple pointed out . @kiv_apple所指出的 ,使这项工作唯一的方法就是泛型。 With your generated code, instances of CustomB may always contain references to A instances in the codes list. 使用生成的代码, CustomB实例可能始终在codes列表中包含对A实例的引用。 There is no way you can restrict that without touching the class definition of B . 在没有触及B的类定义的情况下,您无法限制它。

As this is not possible in your case, you have to find a workaround. 由于在您的情况下这是不可能的,因此您必须找到一种解决方法。 One way to go could be defining a custom, differently named getter (without Lombok) that only returns those elements of codes that are instances of CustomB . 一种CustomB方法是定义一个自定义的,名为不同的getter(不带Lombok),该方法仅返回那些作为CustomB实例的codes元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM