[英]How to print Java Marker Annotations?
I have just begun reading into Java annotations. 我刚刚开始阅读Java批注。 I need to print out all the three annotations written above the checkprime method but it is only printing the first.Seems like a stupid question to ask but am stuck and not being able to find the answer anywhere.
我需要打印出在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();
}
}
}
You need to add @Retention(RetentionPolicy.RUNTIME)
to the rest of your annotations, like this: 您需要将
@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();
}
Without it your code is only aware of the first annotation at runtime, the others will not be available. 没有它,您的代码将仅在运行时知道第一个注释,而其他注释将不可用。
Only one of them is annotated with @Retention(RetentionPolicy.RUNTIME)
. 其中只有一个带有
@Retention(RetentionPolicy.RUNTIME)
注释。 the other ones default to the CLASS policy, which isn't kept at runtime by the VM. 其他默认为CLASS策略,VM不会在运行时保留该策略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.