我应该用 XmlJavaTypeAdapters 注释哪些包信息?

2022-01-19 00:00:00 java jaxb

我研究过 Blaise Doughan 对此主题的问题的回答,但还有其他问题.

I've studied Blaise Doughan's answer to a question on this subject but have a further question.

XmlJavaTypeAdapters 允许您列出一堆 XmlJavaTypeAdapter 注释,每个注释控制 JAXB 如何将不可绑定类型映射到可绑定类型.

XmlJavaTypeAdapters lets you list a bunch of XmlJavaTypeAdapter annotations, each of which governs how a non-bindable type is mapped to a bindable type by JAXB.

您可以在包级别使用此注解.这样做时,每个 XmlJavaTypeAdapter 注释都需要完全指定其 type() 属性.

You can use this annotation at the package level. When you do so, every XmlJavaTypeAdapter annotation needs its type() attribute fully specified.

似乎没有要求被注释的包与正在适应的不可绑定类型的包有任何关系.既方便又美观.

There does not appear to be a requirement that the package that is being annotated have anything to do with the package of the non-bindable types being adapted. That is convenient and nice.

然而,这引出了我的下一个问题:如果带注释的包和正在适配的类型的包之间没有关系,那么 JAXB 如何发现包级别的 XmlJavaTypeAdapters 注释?换句话说,它如何知道为潜在的 XmlJavaTypeAdapters 注释咨询哪些包?我可以在我的 .ear 文件的 lib 目录中的一个 .jar 文件中创建一个随机包,其中包含一个巨大的 package-info 用我所有不可绑定类型的所有适配器注释的类?

That, however, leads me to my next question: if there is no relationship between the annotated package and the package of the type being adapted, how does JAXB discover package-level XmlJavaTypeAdapters annotations? How, in other words, does it know which packages to consult for potential XmlJavaTypeAdapters annotations? May I make a random package in, say, a .jar file in my .ear file's lib directory that contains a single, ginormous package-info class that is annotated with all the adapters for all of my non-bindable types?

推荐答案

当 JAXB 运行时加载一个带有 JAXB 注释的类时,它会在与该类相同的包中查找 package-info.java类,并检查它以查找包级注释.因此,虽然 XmlJavaTypeAdapters 不必与不可绑定"类型位于同一包中,但它确实必须与可绑定"类型位于同一包中类型.

When the JAXB runtime loads a JAXB-annotated class, it looks for a package-info.java in the same package as that class, and checks that to look for package-level annotations. So while XmlJavaTypeAdapters doesn't have to reside in the same package as the "non-bindable" types, it does have to reside in the same package as the "bindable" types.

例如,假设我有一个 JAXB 注释类 A,在包 X 中,它在包中具有 B 类型的属性<代码>是.为了绑定 B 属性,假设需要一个类型适配器.该适配器可以在 A 本身中指定,也可以在包 X 中的 package-info.java 中指定.包 Y 几乎是任意的,并且对 JAXB 运行时不感兴趣.

For example, say I have a JAXB-annotated class A, in package X, which has a property of type B in package Y. In order to bind the B property, let's say a type adapter is required. That adapter can be specified in A itself, or it can be specified in the package-info.java in package X. Package Y is pretty much arbitrary, and is of no interest to the JAXB runtime.

我希望这是有道理的.

相关文章