@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Item", propOrder = {
"code",
"name",
"price"
})
@XmlRootElement(name="inventory")
public class Item {
@XmlElement(name="catalog_num", required = true)
protected String code;
@XmlElement(name="catalog_descrip", required = true)
protected String name;
@XmlElement(name="prod_price")
protected double price;
public String getCode() {
return code;
}
JAXBContext databaseJC = JAXBContext.newInstance(Item.class);
Unmarshaller databaseUnmarshaller = databaseJC.createUnmarshaller();
File databaseXML = new File("src/forum6838882/database.xml");
Item item = (Item) databaseUnmarshaller.unmarshal(databaseXML);
我的问题是:
我如何从item对象中获取@XmlElement(name="catalog_num", required = true)
。我需要知道这里的name="catalog_num"
。
答案 0 :(得分:0)
JAXB (JSR-222)未提供内省元数据的API。但是,您可以使用Java Reflection API(java.lang.reflect
)来获取注释并自行检查它们。
<强>演示强>
import java.lang.reflect.*;
import javax.xml.bind.annotation.*;
public class Demo {
public static void main(String[] args) throws Exception {
Field field = Item.class.getDeclaredField("code");
XmlElement xmlElement = field.getAnnotation(XmlElement.class);
System.out.println(xmlElement.name());
}
}
<强>输出强>
catalog_num