2011-06-17 86 views
0

我們可以在Annotation的接口上使用getAnnotations(),但不能使用getAnnotation?爲什麼 當我改變了接口從MyAnno到註釋中followng程序,編譯器不)承認在註釋中定義的一樣str中的數據(等..爲什麼我不能在註釋的引用上使用getAnnotation()?

package british_by_blood; 

import java.lang.annotation.*; 
import java.lang.reflect.*; 

@Retention (RetentionPolicy.RUNTIME) 
@interface Hashingsnr { 
    String str(); 
    int yuiop(); 
    double fdfd(); 
} 


public class German_by_Descent { 
    @Hashingsnr(str = "Annotation Example", yuiop = 100, fdfd = 4.267) 
    public void mymeth(){ 
       German_by_Descent ob = new German_by_Descent(); 
try{ 
    Class c = ob.getClass(); 
    Method m = c.getMethod("mymeth"); 
    Hashingsnr anno = m.getAnnotation(Hashingsnr.class); 
    System.out.println(anno.str() + " " + anno.yuiop() + " " + anno.fdfd()); 

}catch(NoSuchMethodException exc){ 
    System.out.println("Method Not Found"); 
} 
} 
public static void main(String[] args) { 

    German_by_Descent ogb = new German_by_Descent(); 

    ogb.mymeth(); 

} 

} 
+0

我得到下面的輸出:`註釋例100 4.267` - 看起來OK。你在這個例子中沒有`MyAnno`註釋,你能否編輯你的問題以解決*你實際改變了什麼? – 2011-06-17 11:44:33

+0

對不起,這就是Hashingsnr ....每當我把它改爲第26行的註釋(在第一個地方),然後在第27行str,yuiop和fdfd加下劃線給出錯誤找不到符號 – 2011-06-17 11:49:32

+0

對我也適用 – Bohemian 2011-06-17 11:50:07

回答

0

你的程序似乎正常工作。當我運行它時,我會得到以下輸出...

run-single: 
Annotation Example 100 4.267 
BUILD SUCCESSFUL (total time: 12 seconds) 

我是否在您的問題中缺少某些內容?

我也更改爲使用getAnnotations()方法的代碼,並收到了同樣的結果...

final Annotation[] annos = m.getAnnotations(); 

for (Annotation anno : annos) { 
    if (anno instanceof Hashingsnr) { 
     final Hashingsnr impl = (Hashingsnr)anno; 
     System.out.println(impl.str() + " " + impl.yuiop() + " " + impl.fdfd()); 
    } 
} 
1

據我瞭解,你想改變這一行

Hashingsnr anno = m.getAnnotation(Hashingsnr.class); 

Annotation anno = m.getAnnotation(Hashingsnr.class); 

當然,現在anno是類型的0並且該界面沒有定義您的方法str()yuiop()fdfd()。這就是爲什麼編譯器會在下面一行中抱怨。

就像普通的Java類型,你就必須轉換回真正的註解:

System.out.println(
    ((Hashingsnr) anno).str() + " " + 
    ((Hashingsnr) anno).yuiop() + " " + 
    ((Hashingsnr) anno).fdfd()); 
相關問題