理解 Java 中的注解 [英] Understanding annotation in Java

查看:23
本文介绍了理解 Java 中的注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

@Target(ElementType.METHOD)公共@interface Test_Target {公共字符串 doTestTarget();}

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

公共类TestAnnotations {@Test_Target(doTestTarget="Hello World !")私人字符串 str;公共静态无效主(字符串参数[]){new TestAnnotations().doTestTarget();}公共无效 doTestTarget() {System.out.printf("测试目标注解");}}

当我运行这段代码时,它只打印Testing Target annotation

请帮帮我,我对注释完全陌生.

解决方案

注解基本上是一些可以附加到字段、方法、类等的数据.

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

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

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

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

要在运行时访问您的注释和其中包含的值,您需要使用反射.我已将您的 TestAnnotations 类重写如下,以进行快速演示:

import java.lang.reflect.Field;公共类 TestAnnotations {@Test_Target(doTestTarget="Hello World !")私人字符串 str;public static void main(String[] args) 抛出异常 {//我们需要在这里使用 getDeclaredField 因为该字段是私有的.Field field = TestAnnotations.class.getDeclaredField("str");Test_Target ann = field.getAnnotation(Test_Target.class);如果(安!= null){System.out.println(ann.doTestTarget());}}}

当我运行这段代码时,它给了我以下输出:

<前>你好,世界 !

I was trying to go through some online material to learn annotation in java.

In the following code, what happened to my dear "Hello world" string which I passed in this line: @Test_Target(doTestTarget="Hello World !")?

@Target(ElementType.METHOD)
public @interface Test_Target {
   public String doTestTarget();
}

above is the annotation defined and below is its usage

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

When I run this code it is only printing Testing Target annotation

Please help me out, I am completely new to annotation.

解决方案

Annotations are basically bits of data you can attach to fields, methods, classes, etc.

The syntax for declaring annotations in Java is a little awkward. They look a bit like interfaces (they are, after all, declared with @interface), but they aren't really interfaces. I think you might have put the doTestTarget() method in your TestAnnotations class because you thought your annotation was an interface and you needed to implement it. This isn't true - you can delete this method and the call to it from your code if you wish and doing so won't cause you any problems.

Also, you might not have intended to put the annotation on the field str. Annotations apply only to what immediately follows them. As a result, your code doesn't compile, because you've applied your annotation to a field but declared that your annotation can only be applied to methods. Change @Target(ElementType.METHOD) to @Target(ElementType.FIELD) and your code should then compile.

As for what happens to the string Hello World !, it gets written to the .class file and is available to any tool that reads in Java classes. However, it wouldn't necessarily be available in the JVM at runtime. This happens because you didn't specify a @Retention for your @Test_Target annotation. The default value for @Retention is RetentionPolicy.CLASS, which means that the JVM might not bother to load them out of the class file. (See the Javadoc for the RetentionPolicy enum.)

I imagine you want to see some way of reading the value out of this annotation at runtime. If so, I'd recommend adding @Retention(RetentionPolicy.RUNTIME) to your annotation to make sure it will be available at runtime.

To access your annotation and the value contained within it at runtime, you need to use reflection. I've rewritten your TestAnnotations class as follows to give a quick demonstration:

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

When I run this code, it gives me the following output:

Hello World !

这篇关于理解 Java 中的注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆