import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Created by Administrator on 2014-05-14. */ public class AutoBean{ public static void main(String[] args) throws JAXBException { JAXBContext jaxbContext =JAXBContext.newInstance(SimpleObject.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING,"utf-8");//編碼格式 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);//是否省略xml頭信息(<?xml version="1.0" encoding="utf-8" standalone="yes"?>) SimpleObject people = new SimpleObject(); marshaller.marshal(people, System.out); } } @XmlRootElement class SimpleObject{ // @XmlElement public String publicS="publicS"; // @XmlElement protected String protectedS="protectedS"; @XmlElement String defaultS="defaultS"; // @XmlElement private String privateS="privateS"; // public String getPublicS() { // System.out.println("getPublicS"); // return publicS; // } // // public void setPublicS(String publicS) { // System.out.println("setPublicS"); // this.publicS = publicS; // } // public String getProtectedS() { // System.out.println("getProtectedS"); // return protectedS; // } // // public void setProtectedS(String protectedS) { // System.out.println("setProtectedS"); // this.protectedS = protectedS; // } // // public String getDefaultS() { // System.out.println("getDefaultS"); // return defaultS; // } // // public void setDefaultS(String defaultS) { // System.out.println("setDefaultS"); // this.defaultS = defaultS; // } // public String getPrivateS() { System.out.println("getPrivateS"); return privateS; } public void setPrivateS(String privateS) { System.out.println("setPrivateS"); this.privateS = privateS; } }
按照上面的代碼,進行不一樣的註釋能夠發現java
若是一個屬性書public,則會進入xml文件,其餘不會this
若是一個屬性加有@XmlElement標記,則會進入xml文件,即便是private編碼
若是有getter,則getter會被調用(會被調用三次?!!!)code
若是經過屬性和getter均可以訪問則會報錯,這麼說來對於pojo能夠直接用,無需加上註釋xml