0

我刚刚开始阅读 Java 注释。我需要打印出 checkprime 方法上面写的所有三个注释,但它只打印第一个。这似乎是一个愚蠢的问题,但被卡住了,无法在任何地方找到答案。

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();
    }
  }
}
4

2 回答 2

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(); 
  }

没有它,您的代码在运行时只知道第一个注释,其他注释将不可用。

于 2013-01-03T20:07:18.430 回答
1

其中只有一个用 注释@Retention(RetentionPolicy.RUNTIME)。其他默认为 CLASS 策略,VM 不会在运行时保留该策略。

于 2013-01-03T20:08:06.823 回答