您可以将此解决方案与其他类一起使用Input
@XmlAccessorType(XmlAccessType.FIELD)
public class Input
{
@XmlAttribute
private String type;
@XmlAttribute
private String name;
@XmlValue
private String value;
public Input() {}
public Input(String type, String name, String value)
{
this.type = type;
this.name = name;
this.value = value;
}
}
以及实体
变体 1中的其他吸气剂
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
@Id @GeneratedValue
private Long id;
private String firstName = "foo";
private String lastName = "bar";
// getters/setters
@XmlElement(name= "Input")
Input getFirstNameXML()
{
return new Input(String.class.getSimpleName(), "firstName", firstName);
}
@XmlElement(name= "Input")
Input getLastNameXML()
{
return new Input(String.class.getSimpleName(), "lastName", lastName);
}
}
变体 2
@XmlRootElement(name= "PersonInputs")
@XmlAccessorType(XmlAccessType.NONE)
public class Person
{
private Long id;
private String firstName = "foo";
private String lastName = "bar";
// getters/setters
@XmlElement(name = "Input")
List<Input> getList() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
return getInputs(this, "firstName", "lastName"); // fields names
}
}
使用方法getInputs
static List<Input> getInputs(Object thisObj, String ... fields) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException
{
final List<Input> retVal = new ArrayList<Input>();
for (String field : fields)
{
Field f = thisObj.getClass().getDeclaredField(field);
f.setAccessible(true);
retVal.add(new Input(f.getType().getSimpleName(), field, (String )f.get(thisObj)));
}
return retVal;
}