有没有办法从实例(而不是从类)获取Field引用?
这是一个例子:
public class Element {
@MyAnnotation("hello")
public String label1;
@MyAnnotation("world")
public String label2;
}
public class App {
private Element elem = new Element();
public void printAnnotations() {
String elemLabel1 = elem1.label;
String elemLabel2 = elem2.label;
// cannot do elemLabel.getField().getDeclaredAnnotations();
String elemLabel1AnnotationValue = // how ?
String elemLabel2AnnotationValue = // how ?
}
}
很抱歉不太清楚,但我已经知道如何从课程中获取字段(Class - > Field - > DeclaredAnnotations)
我想知道的是如何为特定实例获取Field。 在这个例子中,从elemLabel1字符串实例,我希望能够得到Element.label1的字段。
答案 0 :(得分:2)
你到底是什么意思?在Field
上定义了Class
。您可以获取特定实例的值: -
private static class Test {
private int test = 10;
}
public static void main(String[] args) throws Exception {
final Test test = new Test();
final Field field = Test.class.getDeclaredField("test");
field.setAccessible(true);
final int value = field.getInt(test);
System.out.println(value);
}
class Test
有Field
名为test
。任何Test
都是如此 - 它在Class
中定义。 class
的实例具有Field
的特定值,在本例中为10
。可以使用getXXX
或get
方法检索特定实例。
修改强>
从您问题中的代码看,您希望Annotation
字段的值不是class
字段的值。
在Java中,注释中的值是编译时常量,因此也在class
而不是实例级别定义。
public class Element {
@MyAnnotation("l")
public String label;
}
在您的示例中,MyAnnotation
值字段必须等于<{>每个 1
实例的Element
。
答案 1 :(得分:2)
Field
属于班级。因此,您实际上想要执行以下操作:
elemLabel.getClass().getField("theFieldName").getDeclaredAnnotations();
但是,虽然您的字段为public
,但通常所有字段都应为private
。在这种情况下,请使用getDeclaredField()
代替getField()
。
EDIT
在使用该字段之前,您必须致电field.setAccessible(true)
。