从实例获取字段?

时间:2013-05-13 06:24:45

标签: java

有没有办法从实例(而不是从类)获取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的字段。

2 个答案:

答案 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 TestField名为test。任何Test都是如此 - 它在Class中定义。 class的实例具有Field的特定值,在本例中为10。可以使用getXXXget方法检索特定实例。

修改

从您问题中的代码看,您希望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)