您的位置:首页 > 编程语言 > Java开发

了解Java中的注解

2020-06-05 16:24 330 查看

介绍

本文将讨论用Java创建注解的方法。还有如何将注解应用于其他声明。最后,讨论一下如何在运行时使用Reflection获得注解信息。

背景

注解是J2SE 5引入的一项新功能,允许程序员将称为元数据的其他信息嵌入Java源文件中。注解不会改变程序的执行,但是在开发和部署期间,各种工具都可以使用使用注解嵌入的信息。

使用代码

创建注解与创建接口相似。只不过注解声明前面有一个

@
符号。注解声明本身使用注解进行
@Retention
注解。该
@Retention
注解用于指定保留策略,可以是
SOURCE
CLASS
RUNTIME

  • RetentionPolicy.SOURCE
    仅在源文件中保留注解,并在编译期间将其丢弃。
  • RetentionPolicy.CLASS
    将注解存储在.class文件中,但在运行时不可用。
  • RetentionPolicy.RUNTIME
    将注解存储在.class文件中,并使其在运行时可用。
// Specifying runtime retention policy
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation
{
String author();    // Annotation member
String date();      // Annotation member
}

注解会隐式扩展

Annotation
接口。注解的主体由不带主体的方法声明组成。这些方法像字段一样工作。

在上面的例子中,我已经创建了两个部件,

author
date
以表示关于创建者的信息,并且类和方法的写入日期。

创建注解后,可以将其应用于类,方法,字段,参数,枚举等。在对声明应用注解时,必须为其成员提供如下值:

// Applying annotation to the class
@MyAnnotation(author="Azim",date="22/10/2011,23/10/2011")
public class Test
{
// Applying annotation to the method
@MyAnnotation(author="Azim",date="22/10/2011")
public static void testMethod()
{
System.out.println("Welcome to Java");
System.out.println("This is an example of Annotations");
}
public static void main(String args[])
{
testMethod();
showAnnotations();
}

可以在运行时使用Reflection来查询注解,如下所示:

public static void showAnnotations()
// Function to show annotation information
{
Test test=new Test(); // Instantiating Test class
try
{
Class c=test.getClass(); // Getting Class reference
Method m=c.getMethod("testMethod"); // Getting Method reference
// Getting Class annotation
MyAnnotation annotation1=
(MyAnnotation)c.getAnnotation(MyAnnotation.class);
// Getting Method annotation
MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
// Displaying annotation information
System.out.println("Author of the class: "+annotation1.author());
// Displaying annotation information
System.out.println("Date of Writing the class: "+annotation1.date());
// Displaying annotation information
System.out.println("Author of the method: "+annotation2.author());
// Displaying annotation information
System.out.println("Date of Writing the method: "+annotation2.date());
}
catch(NoSuchMethodException ex)
{
System.out.println("Invalid Method..."+ex.getMessage());
}
}

在上面的代码中,我查询了应用于类

Test
以及method的注解
testMethod()

要获取该类的注解信息,请使用以下语句:

MyAnnotation annotation1=(MyAnnotation)c.getAnnotation(MyAnnotation.class);

要获取该方法的注解信息,请使用以下语句:

MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);

通过使用注解对象来打印注解信息。

问题:注解声明后,在运行期如何查询它的信息?

答:使用Reflection来查询注解

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: