2013-05-13 75 views
0

有什麼辦法從一個實例(不是從一個類)獲取一個字段引用?從實例獲取字段?

這是一個例子:

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 ? 
    } 
} 

對不起,我不是太清楚,但我已經知道如何從一個類中獲取的字段(類 - >字段 - > DeclaredAnnotations)

我在想什麼是如何獲得特定實例的字段。 在這個例子中,從elemLabel1字符串實例中,我希望能夠得到Element.label1的字段。

+0

對我來說,好像你在你的標題中提出了不同的樣品。你是否想要獲得註釋或字段? – 2013-05-13 06:25:54

+0

在獲得特定領域的註解之前,它實際上首先獲得了領域,因此這關係到我認爲獲得領域。 – bertie 2013-05-13 06:28:03

+0

從這個問題的表達方式來看,這聽起來像你已經知道如何從一個類中獲取數據,但是你想從一個實例中獲取信息。如果是這樣,'.getClass()'可能適合你。 – 2013-05-13 06:30:06

回答

2

你究竟是什麼意思? A 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有一個叫Fieldtest。任何Test都是如此 - 它在Class中定義。 class的實例對於該Field具有特定值,在這種情況下爲10。這可以使用getXXXget方法檢索特定實例。

編輯

從你的問題的代碼,它看起來像你想的Annotation領域class場的不是價值的價值。

在Java中,註釋中的值是編譯時間常量,因此也定義在class而不是實例級別。

public class Element { 
    @MyAnnotation("l") 
    public String label; 
} 

在您的例子中,MyAnnotation值字段必須等於1Element實例。

+0

使Test類成爲靜態的要點是什麼 – 2013-05-13 06:34:18

+0

所以我可以在'static' main'方法中引用它,當它在同一個'class'文件中定義時。只是爲了讓這個例子更加簡潔。 – 2013-05-13 06:36:56

+0

鮑里斯你好。是的,這是班級定義。但在我的程序中,我無法知道包含帶註釋字符串的類。我所擁有的只是String實例(可能作爲方法參數傳遞)。我想知道我是否只能得到該字符串實例的字段。 – bertie 2013-05-13 06:39:40

2

Field屬於類。因此實際上要做到以下幾點:

elemLabel.getClass().getField("theFieldName").getDeclaredAnnotations();

不過雖然你的字段是public通常各個領域應該是private。在這種情況下,請使用getDeclaredField()而不是getField()

編輯 您必須在使用該字段之前調用field.setAccessible(true)

+0

感謝Field屬於Class的筆記。但就我而言,String只是一個字符串,因爲程序可能不知道包含該String的Class是什麼。所以我想知道我是否可以獲取字符串實例的字段。 – bertie 2013-05-13 06:38:06