更新时间:2022-04-10 04:58:49
假设我们有注释实体
@XmlRootElement
public class Product {
String name;
@XmlElement(name="sss")
public void setName(String name) {
this.name = name;
}
}
以下代码将使用 java Reflection API 。这里'product'是Product class的对象
Code below will print "sss" using java Reflection API. Here 'product' is an object of Product class
import java.lang.reflect.Method;
...
Method m = product.getClass().getMethod("setName",String.class);
XmlElement a = m.getAnnotation(XmlElement.class);
String nameValue = a.name();
System.out.println(nameValue);
如果您需要从私有字段获取@XmlElement注释属性,可以使用这样的东西:
If you need to get @XmlElement annotation attribute from private field, you could use something like this:
Field nameField = product.getClass().getDeclaredField("name");
nameField.setAccessible(true);
XmlElement a = nameField.getAnnotation(XmlElement.class);
String nameValue = a.name();
System.out.println(nameValue);