问题
I have a class with a field which looks like this
@XmlElement(name = "Name", namespace = "a:b:c:1", required = true)
protected String firstName
I want to use JXPath like this
String name = (String) context.getValue("Name");
But it doesn't recognize the XMLElement name attribute. Is there any way to make it do so?
回答1:
I don't think you can. JXPath allows navigation of bean hierarchies using the standard bean get/is notation, but doesn't provide a means of accessing annotations on a field.
I think you should perhaps look at this answer re. finding annotations. Perhaps you can combine with a JXPath solution ?
回答2:
I did this as Brian suggested
Field[] fields = rq.getClass().getDeclaredFields();
Map<String, String> annotationMap = new HashMap<>();
for(Field field:fields)
{
if(field.getAnnotation(XmlElement.class).name().equals("Name"))
{
annotationMap.put("Name", field.getName());
}
}
String name = (String) context.getValue(annotationMap.get("Name"));
System.out.println(name);
But won't this approach be tedious if I have a 100 fields or more? Is there a better way to do this?
来源:https://stackoverflow.com/questions/26947096/how-to-make-jxpath-read-xmlelement-name-attribute-instead-of-actual-field-name