Java 如何创建自定义注解
当我们开始学习Java时,常常会对像@override和@inherited这样的符号感到困惑。它们是一种特殊类型的标记,被称为注解,可以应用于类、方法、字段、参数和代码的其他元素。Java提供了支持一些内置注解,但我们也可以创建自己的注解。在本文中,我们将学习如何创建和使用自定义注解。
在Java中创建自定义注解
在创建自定义注解之前,让我们先了解Java中注解的基础知识。
注解
它们是Java的一项强大功能,允许我们向我们的代码添加元数据。这里,元数据的意思是关于特定代码块的附加信息。它们可以用于各种目的,包括文档、验证、测试、依赖注入等。它们以’@’符号开头,可以有可选的属性提供额外的信息。
Java支持两种类型的注解:内置注解和自定义注解。内置注解具有预定义的含义和行为。
以下是一些内置注解:
- @Override :它指示一个方法覆盖了超类或接口中的另一个方法。
-
@Deprecated :它用于将元素标记为过时,以便在使用时生成警告。
-
@SuppressWarnings :抑制编译器警告。
到目前为止,我们已经介绍了注解及其一些预定义注解。现在,让我们讨论如何创建自定义注解。
创建自定义注解
第一步是使用@interface关键字和注解名称来声明注解。然后,下一步是添加一些描述新创建的注解的属性。属性可以是一些变量。
语法
@interface nameOfAnnotation { // declaration
// Attributes
}
@nameOfAnnotation( values ) // initialization
示例1
在下面的示例中,我们将创建一个名为“作者详细信息”(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
示例2
在以下示例中,我们将声明一个名为’Author_details’的注释,以及它的两个默认属性’name’和’email’。要定义默认属性,我们需要使用’default’关键字。
// declaring the annotation
@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("This is an example of Annotation");
}
}
输出
This is an example of Annotation
示例3
在下面的示例中,我们将创建并使用单个值注释。
// declaring the annotation
@interface Author_details {
// attributes of annotation
String name() default "Shriansh Kumar";
}
// to use the annotation
@Author_details
public class Example3 {
public static void main(String[] args) {
System.out.println("This is an example of Annotation");
}
}
输出
This is an example of Annotation
结论
注解只是告诉我们有关代码块的信息,它不会影响整个代码的工作。在本文中,我们首先学习了内置注解,然后在后面的部分中,我们通过示例讨论了创建和使用自定义注解的过程。