理解Java中的注释

Anu*_*pta 11 java annotations

我试图通过一些在线资料来学习java中的注释.

在下面的代码中,我在这行传递的亲爱的"Hello world"字符串发生了什么:@Test_Target(doTestTarget="Hello World !")

@Target(ElementType.METHOD)
public @interface Test_Target {
   public String doTestTarget();
}
Run Code Online (Sandbox Code Playgroud)

上面是定义的注释,下面是它的用法

public class TestAnnotations {
   @Test_Target(doTestTarget="Hello World !")
   private String str;
   public static void main(String arg[]) {
      new TestAnnotations().doTestTarget();
   }
   public void doTestTarget() {
      System.out.printf("Testing Target annotation");
   }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,它只是打印 Testing Target annotation

请帮帮我,我对注释是全新的.

Luk*_*ard 22

注释基本上是可以附加到字段,方法,类等的数据位.

在Java中声明注释的语法有点尴尬.它们看起来有点像接口(毕竟它们是声明的@interface),但它们并不是真正的接口.我想你可能已经把这个doTestTarget()方法放在你的TestAnnotations类中,因为你认为你的注释是一个接口而你需要实现它.事实并非如此 - 如果您愿意,可以删除此方法并从代码中调用它,这样做不会给您带来任何问题.

此外,您可能没有打算将注释放在字段上str.注释仅适用于紧随其后的内容.因此,您的代码无法编译,因为您已将注释应用于字段,但声明您的注释只能应用于方法.更改@Target(ElementType.METHOD)@Target(ElementType.FIELD),然后你的代码应该编译.

至于字符串会发生什么Hello World !,它会被写入.class文件,并且可用于读取Java类的任何工具.但是,它不一定在运行时在JVM中可用.发生这种情况是因为您没有@Retention@Test_Target注释指定a .@Retentionis 的默认值RetentionPolicy.CLASS,这意味着JVM可能无需将它们加载到类文件中.(有关RetentionPolicy枚举,请参阅Javadoc.)

我想你想看到一些在运行时从这个注释中读取值的方法.如果是这样,我建议添加@Retention(RetentionPolicy.RUNTIME)到您的注释,以确保它在运行时可用.

要在运行时访问注释及其中包含的值,您需要使用反射.我TestAnnotations按照以下方式重写了你的课程,以便快速演示:

import java.lang.reflect.Field;

public class TestAnnotations {

   @Test_Target(doTestTarget="Hello World !")
   private String str;

   public static void main(String[] args) throws Exception {
      // We need to use getDeclaredField here since the field is private.
      Field field = TestAnnotations.class.getDeclaredField("str");
      Test_Target ann = field.getAnnotation(Test_Target.class);
      if (ann != null) {
         System.out.println(ann.doTestTarget());
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,它给我以下输出:

Hello World !