Java @Target 注解

Java @Target 注解

当我们开始学习Java时,我们经常会对像@override和@inherited这样写在代码块中的符号感到困惑。它们是一种特殊的标签,被称为注解(Annotations),可以应用于类、方法、字段、参数和代码的其他元素。@Target注解是一种指定适用于哪个代码块元素的定义注解类型的元注解之一。不要被这些术语困惑,我们将在本文中澄清所有疑惑和困惑。

Java的@Target注解

我们需要先了解什么是注解,以及它们在Java中的作用。

注解

它们是Java的一个强大特性,允许我们向代码中添加元数据。在这里,元数据的意思是关于特定代码块的附加信息。它们可以用于各种目的,包括文档编写、验证、测试、依赖注入等等。它们以’@’符号开头,可以具有可选的属性,提供附加信息。

Java支持两种类型的注解:内置注解和自定义注解。内置注解具有预定义的含义和行为。

下面是一些内置注解-

  • @Override - 它表示一个方法覆盖了超类或接口中的另一个方法。

  • @Deprecated - 它用于标记一个元素已过时,以在使用时生成警告。

  • @SuppressWarnings - 抑制编译器警告。

到目前为止,我们已经了解了注解和一些预定义注解。现在,让我们讨论如何创建自定义注解。

创建自定义注解

第一步是使用@interface关键字声明注解的名称。然后,在新创建的注解中添加一些描述的属性。属性可以是一些变量。

语法

@interface nameOfAnnotation { // declaration
   // Attributes
}
@nameOfAnnotation( values ) // initialization

示例

在下面的示例中,我们将创建一个名为’Author_details’的注释,还有它的两个必填属性’name’和’email’。

// declaring the annotation
@interface Author_details {
   // attributes of annotation
   String name(); 
   String email(); 
}
// to use the annotation
@Author_details(name = "Shriansh Kumar", email = "shriansh.kumar@tp.com")
public class Example1 {
   public static void main(String[] args) {
      System.out.println("This is an example of Annotation");
   }
}

输出

This is an example of Annotation

如何使用@Target注解对注解进行注释

有时用户创建的注解可能无法传达其全部目的。针对这种情况,Java提供了四个元注解,分别是@Documentation、@Target、@Retention和@Inherited,用于为用户自定义的注解提供另一种形式的元数据注解。这将帮助编译器在编译期间强制实施所需的特性。

@Target注解接受一个值数组,其参数是来自java.lang.annotation.ElementType枚举的元素。ElementType枚举定义了可以在Java中进行注解的可能种类。这些值包括:

  • ANNOTATION_TYPE −注解类型声明

  • CONSTRUCTOR −构造函数声明

  • FIELD −字段声明

  • LOCAL_VARIABLE −局部变量声明

  • METHOD −方法声明

  • PACKAGE −包声明

  • PARAMETER −参数声明

  • TYPE −类、接口、枚举或记录声明

  • TYPE_PARAMETER −类型参数声明

  • TYPE_USE −类型使用

语法

@Target({ElementType.nameOfanyValues})
@interface nameOfCustomAnnotation {
   // attributes of annotation come here
}

示例

在这个例子中,我们将使用@Target创建一个自定义注解,其值为’TYPE’,这意味着该注解适用于类、接口和枚举。

import java.lang.annotation.*;
// declaring the annotations
@Target({ElementType.TYPE})
@interface Author_details {
   // attributes of annotation
   String name() default "Shriansh Kumar"; 
   String email() default "shriansh.kumar@tp.com"; 
}
// to use the annotation
@Author_details
public class Example2 {
   public static void main(String[] args) {
      System.out.println("Annotating an Annotation using @Target");
   }
}

输出

Annotating an Annotation using @Target

结论

在本文中,我们首先了解了内置注释,然后在后面的部分讨论了使用示例程序创建和使用自定义注释的过程。我们还发现了使用@Target注释对另一个注释进行注释的用法。请注意,注释只是告诉我们有关代码块的信息,不影响整个代码的工作。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程