我正在尝试让JAXB与我的常规类一起使用,但是,它似乎不起作用,但是Java版本却可以。这是代码…
以下是方案:
如果2和3不加注释,则可以正常工作。
如果1和4不加注释,我得到:
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions groovy.lang.MetaClass is an interface, and JAXB can't handle interfaces.
如果1和5不加注释,我得到:
javax.xml.bind.JAXBException: class org.oclc.presentations.simplejaxb.PlayerGroovy nor any of its super class is known to this context.
有任何想法吗?
Java:
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Player { }
Groovy:
import javax.xml.bind.annotation.XmlRootElement @XmlRootElement public class PlayerGroovy { }
测试:
import org.junit.Test import javax.xml.bind.JAXBContext import javax.xml.bind.Marshaller import org.junit.Assert class PlayerTest { @Test public void testJaXB(){ //1 PlayerGroovy player = new PlayerGroovy() //2 Player player = new Player() StringWriter writer = new StringWriter(); //3 JAXBContext context = JAXBContext.newInstance(Player.class); //4 JAXBContext context = JAXBContext.newInstance(PlayerGroovy.class); //5 JAXBContext context = JAXBContext.newInstance(PlayerGroovy.getClass()); Marshaller m = context.createMarshaller(); m.marshal(player, writer); println(writer) Assert.assertTrue(true) } }
取消注释1和4是使用Groovy设置JAXB的正确方法。它不起作用的原因是每个Groovy类都具有metaClass属性。JAXB试图将其公开为显然失败的JAXB属性。由于您自己没有声明metaClass属性,因此无法对其进行注释以使JAXB忽略它。而是将XmlAccessType设置为NONE。这将禁用JAXB的属性自动发现以将其公开为XML元素。之后,您需要显式声明要公开的任何字段。
例:
@XmlAccessorType( XmlAccessType.NONE ) @XmlRootElement public class PlayerGroovy { @XmlAttribute String value }