2013-01-03 91 views
0

我剛開始閱讀Java註釋。我需要打印所有在checkprime方法上面寫的所有三個註釋,但它只是打印第一個。看起來像一個愚蠢的問題,但我被困住了,無法在任何地方找到答案。如何打印Java標記註釋?

import java.io.*; 
import java.lang.annotation.Annotation; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.reflect.Method; 

@Retention(RetentionPolicy.RUNTIME) 

@interface MyMarker 
    { 

    } 

@interface MyMarker1 
    { 
String author(); 
    } 

@interface MyMarker2 
    { 
String author(); 
String module(); 
double version(); 
    } 

public class Ch10Lu1Ex4 
{ 
@MyMarker 
@MyMarker1(author = "Ravi") 
@MyMarker2(author = "Ravi", module = "checkPrime", version = 1.1) 
public static void checkprime(int num) 
    { 
     int i; 
     for (i=2; i < num ;i++) 
     { 
      int n = num%i; 
      if (n==0) 
      { 
      System.out.println("It is not a prime number"); 
      break; 
      } 
     } 
      if(i == num) 
      { 

       System.out.println("It is a prime number"); 
      } 
} 


public static void main(String[] args) 
    { 
    try 
     { 
     Ch10Lu1Ex4 obj = new Ch10Lu1Ex4(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Enter a number:"); 
     int x = Integer.parseInt(br.readLine()); 
     obj.checkprime(x); 
     Method method = obj.getClass().getMethod("checkprime", Integer.TYPE); 
     Annotation[] annos = method.getAnnotations(); 
     for(int i=0;i<annos.length;i++) 
      { 
      System.out.println(annos[i]); 
      } 
     } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 

回答

2

您需要添加@Retention(RetentionPolicy.RUNTIME)到您的註釋的其餘部分,像這樣:

@Retention(RetentionPolicy.RUNTIME) 
@interface MyMarker 
{ 
} 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyMarker1 
    { 
String author(); 
    } 

@Retention(RetentionPolicy.RUNTIME) 
@interface MyMarker2 
    { 
String author(); 
String module(); 
double version(); 
    } 

沒有它,你的代碼是隻知道在運行時的第一個註釋的,其他人將無法使用。

1

其中只有一個註釋爲@Retention(RetentionPolicy.RUNTIME)。其他的默認爲CLASS策略,而不是由VM在運行時保留。