2013-01-03 48 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在运行时保留。