简体   繁体   中英

Configure JAXB unmarshaller to handle class having both acessor methods and field

Is it possible to configure JAXB context (for unmarshaller) itself so that it may instantiate context for the class A which has both accessors getField()/setField() and the field? Class A is not modifiable: it is either 3rd party or generated.

class A {
    public int field;
    public int getField();
    public void setField(int field);
}

Standard JAXBContext instantiation

   JAXBContext jaxbContext = JAXBContext.newInstance(A.class);

would give the following exception

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions

Class has two properties of the same name "field"
    this problem is related to the following location:
        at public int com.thecompany.A.getField()
        at com.thecompany.A
    this problem is related to the following location:
        at public int com.thecompany.A.field
        at com.thecompany.A

which could be resolved by annotating the class with

@XmlAccessorType(XmlAccessType.FIELD)

but this is not the acceptable solution.

Is there way to keep the class definition untouched and be able to read its instances from XML file? (may be not JAXB?)

UPD: found same question answered: JAX-B - How to map a schema element to an existing Java class

Alternatively, use http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted as in this answer: Creating Jaxb classes from xml without schema ; nice tutorial is given at http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html

JAXB external bindings allows you to marshall/unmarshall without changing the source, which I believe is what you're asking for.

http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/2.0/tutorial/doc/JAXBUsing4.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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