[英]Why XmlAdapter in JAXB is abstract class?
I always use interface when there is no common implementation between the subclasses.当子类之间没有共同的实现时,我总是使用接口。 However, the built-in
XmlAdapter
in JAXB is an abstract class, and ALL the methods there are abstract, why it's not made interface instead of abstract class?但是
XmlAdapter
中内置的XmlAdapter是一个抽象的class,而且里面的所有方法都是抽象的,为什么不做成接口而不是抽象的class呢? There should be a reason.应该是有原因的。
XmlAdapter
defines two abstract methods, and also a default no arg protected constructor. XmlAdapter
定义了两个抽象方法,以及一个默认的无参数保护构造函数。
Unmarshaller
s and Marshaller
s creates the instances of XmlAdapter
using the default constructor (unless an instance is provided with setAdapter
). Unmarshaller
和Marshaller
使用默认构造函数创建XmlAdapter
的实例(除非实例与setAdapter
一起提供)。
My initial thought was that the reason was ensuring there is always a default no-arg constructor for Marshaller
and Unmarshaller
, but as you stated, if a subclass of XmlAdapter
declared an non no-arg constructor, that would make the default constructor of XmlAdapter
not visible.我最初的想法是,原因是确保
Marshaller
和Unmarshaller
总是有一个默认的无参数构造函数,但正如你所说,如果XmlAdapter
的子类声明了一个非无参数构造函数,那将使XmlAdapter
的默认构造函数不可见的。 In fact, an XmlAdapter
implementation that added a constructor with args, and did'nt provide the no-arg constructor, would cause the Marshall/Unmarshall operation to fail unless instances where provided with setAdapter
methods.事实上,一个
XmlAdapter
实现添加了一个带 args 的构造函数,并且没有提供无参数的构造函数,这将导致 Marshall/Unmarshall 操作失败,除非实例提供了setAdapter
方法。
So, there is not practical reason to use and abstract class instead of an interface with the current implementation .因此,没有实际理由使用和抽象 class 而不是与当前实现的接口。
My guess is this was a design decision as using and abstract class is best suited from an evolution perspective.我的猜测是这是一个设计决策,因为从进化的角度来看,使用和抽象 class 最适合。 If for example, at some point some kind of common initialization where required in the constructor, it could be implemented on the now empty constructor.
例如,如果在构造函数中需要某种常见的初始化,它可以在现在为空的构造函数上实现。 Or if a method where required in the
XmlAdapter
to marshall a list of objects, it could be implemented with something like this:或者,如果
XmlAdapter
中需要一个方法来编组对象列表,则可以使用如下方式实现:
public List<ValueType> marshalList(List<BoundType> list) throws Exception {
List<ValueType> result = new ArrayList<>();
for (BoundType b: list) {
result.add(marshal(b));
}
return result;
}
And JAXB internal classes could use this method without the need of modifying any of the adapter implementations. JAXB 内部类可以使用这种方法,而无需修改任何适配器实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.