Các loại chú thích Java

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về các loại chú thích Java khác nhau với sự trợ giúp của các ví dụ.

Chú thích Java là siêu dữ liệu (dữ liệu về dữ liệu) cho mã nguồn chương trình của chúng tôi. Có một số chú thích được xác định trước được cung cấp bởi Java SE. Hơn nữa, chúng tôi cũng có thể tạo các chú thích tùy chỉnh theo nhu cầu của mình.

Nếu bạn không biết chú thích là gì, hãy truy cập hướng dẫn chú thích Java.

Các chú thích này có thể được phân loại thành:

1. Chú thích được xác định trước

  • @Deprecated
  • @Override
  • @SuppressWarnings
  • @SafeVarargs
  • @FunctionalInterface

2. Chú thích tùy chỉnh

3. Meta-annotations

  • @Retention
  • @Documented
  • @Target
  • @Inherited
  • @Repeatable

Các loại chú thích được xác định trước

1. @Deprecated

Các @Deprecatedchú thích là một chú thích đánh dấu cho biết các phần tử (lớp, phương pháp, lĩnh vực, vv) bị phản đối và đã được thay thế bởi một yếu tố mới.

Cú pháp của nó là:

 @Deprecated accessModifier returnType deprecatedMethodName() (… ) 

Khi một chương trình sử dụng phần tử đã được khai báo không được chấp nhận, trình biên dịch sẽ tạo ra một cảnh báo.

Chúng tôi sử dụng @deprecatedthẻ Javadoc để ghi lại phần tử không dùng nữa.

 /** * @deprecated * why it was deprecated */ @Deprecated accessModifier returnType deprecatedMethodName() (… ) 

Ví dụ 1: Ví dụ về chú thích @Deprecated

 class Main ( /** * @deprecated * This method is deprecated and has been replaced by newMethod() */ @Deprecated public static void deprecatedMethod() ( System.out.println("Deprecated method"); ) public static void main(String args()) ( deprecatedMethod(); ) ) 

Đầu ra

 Phương pháp không được chấp nhận 

2. @Override

Các @Overridequy định cụ thể chú thích rằng một phương pháp của một lớp con override phương thức của lớp cha có cùng tên phương pháp, kiểu trả về, và danh sách tham số.

Nó không bắt buộc phải sử dụng @Overridekhi ghi đè một phương thức. Tuy nhiên, nếu chúng ta sử dụng nó, trình biên dịch sẽ báo lỗi nếu có gì đó sai (chẳng hạn như kiểu tham số sai) trong khi ghi đè phương thức.

Ví dụ 2: Ví dụ về chú thích @Override

 class Animal ( // overridden method public void display()( System.out.println("I am an animal"); ) ) class Dog extends Animal ( // overriding method @Override public void display()( System.out.println("I am a dog"); ) public void printMessage()( display(); ) ) class Main ( public static void main(String() args) ( Dog dog1 = new Dog(); dog1.printMessage(); ) ) 

Đầu ra

 Tôi là một con chó 

Trong ví dụ này, bằng cách tạo một đối tượng dog1 của lớp Dog, chúng ta có thể gọi phương thức printMessage () của nó sau đó thực thi display()câu lệnh.

display()được định nghĩa trong cả hai lớp, nên phương thức của lớp con Dog ghi đè phương thức của lớp cha Animal. Do đó, display()lớp con được gọi.

3. @SuppressWarnings

Như tên cho thấy, @SuppressWarningschú thích hướng dẫn trình biên dịch loại bỏ các cảnh báo được tạo ra trong khi chương trình thực thi.

Chúng tôi có thể chỉ định loại cảnh báo sẽ bị loại bỏ. Các cảnh báo có thể bị loại bỏ là dành riêng cho trình biên dịch nhưng có hai loại cảnh báo: không dùng nữakhông được chọn .

Để loại bỏ một danh mục cảnh báo cụ thể, chúng tôi sử dụng:

 @SuppressWarnings("warningCategory") 

Ví dụ,

 @SuppressWarnings("deprecated") 

Để loại bỏ nhiều loại cảnh báo, chúng tôi sử dụng:

 @SuppressWarnings(("warningCategory1", "warningCategory2")) 

Ví dụ,

 @SuppressWarnings(("deprecated", "unchecked")) 

Category deprecatedhướng dẫn trình biên dịch loại bỏ các cảnh báo khi chúng tôi sử dụng phần tử không dùng nữa.

Category uncheckedhướng dẫn trình biên dịch loại bỏ các cảnh báo khi chúng ta sử dụng các loại thô.

Và, các cảnh báo không xác định được bỏ qua. Ví dụ,

 @SuppressWarnings("someundefinedwarning") 

Ví dụ 3: Ví dụ về chú thích @SuppressWarnings

 class Main ( @Deprecated public static void deprecatedMethod() ( System.out.println("Deprecated method"); ) @SuppressWarnings("deprecated") public static void main(String args()) ( Main depObj = new Main(); depObj. deprecatedMethod(); ) ) 

Đầu ra

 Phương pháp không được chấp nhận 

Ở đây, deprecatedMethod()đã được đánh dấu là không dùng nữa và sẽ đưa ra cảnh báo trình biên dịch khi được sử dụng. Bằng cách sử dụng @SuppressWarnings("deprecated")chú thích, chúng ta có thể tránh các cảnh báo của trình biên dịch.

4. @SafeVarargs

The @SafeVarargs annotation asserts that the annotated method or constructor does not perform unsafe operations on its varargs (variable number of arguments).

We can only use this annotation on methods or constructors that cannot be overridden. This is because the methods that override them might perform unsafe operations.

Before Java 9, we could use this annotation only on final or static methods because they cannot be overridden. We can now use this annotation for private methods as well.

Example 4: @SafeVarargs annotation example

 import java.util.*; class Main ( private void displayList(List… lists) ( for (List list : lists) ( System.out.println(list); ) ) public static void main(String args()) ( Main obj = new Main(); List universityList = Arrays.asList("Tribhuvan University", "Kathmandu University"); obj.displayList(universityList); List programmingLanguages = Arrays.asList("Java", "C"); obj.displayList(universityList, programmingLanguages); ) ) 

Warnings

 Type safety: Potential heap pollution via varargs parameter lists Type safety: A generic array of List is created for a varargs parameter 

Output

 Note: Main.java uses unchecked or unsafe operations. (Tribhuvan University, Kathmandu University) (Tribhuvan University, Kathmandu University) (Java, C) 

Here, List … lists specifies a variable-length argument of type List. This means that the method displayList() can have zero or more arguments.

The above program compiles without errors but gives warnings when @SafeVarargs annotation isn't used.

When we use @SafeVarargs annotation in the above example,

 @SafeVarargs private void displayList(List… lists) (… ) 

We get the same output but without any warnings. Unchecked warnings are also suppressed when we use this annotation.

5. @FunctionalInterface

Java 8 first introduced this @FunctionalInterface annotation. This annotation indicates that the type declaration on which it is used is a functional interface. A functional interface can have only one abstract method.

Example 5: @FunctionalInterface annotation example

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method ) 

If we add another abstract method, let's say

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method public void secondMethod(); // this throws compile error ) 

Now, when we run the program, we will get the following warning:

 Unexpected @FunctionalInterface annotation @FunctionalInterface MyFuncInterface is not a functional interface multiple non-overriding abstract methods found in interface MyFuncInterface 

It is not mandatory to use @FunctionalInterface annotation. The compiler will consider any interface that meets the functional interface definition as a functional interface.

We use this annotation to make sure that the functional interface has only one abstract method.

However, it can have any number of default and static methods because they have an implementation.

 @FunctionalInterface public interface MyFuncInterface( public void firstMethod(); // this is an abstract method default void secondMethod() (… ) default void thirdMethod() (… ) ) 

Custom Annotations

It is also possible to create our own custom annotations.

Its syntax is:

 (Access Specifier) @interface ( DataType () (default value); ) 

Here is what you need to know about custom annotation:

  • Annotations can be created by using @interface followed by the annotation name.
  • The annotation can have elements that look like methods but they do not have an implementation.
  • The default value is optional. The parameters cannot have a null value.
  • The return type of the method can be primitive, enum, string, class name or array of these types.

Example 6: Custom annotation example

 @interface MyCustomAnnotation ( String value() default "default value"; ) class Main ( @MyCustomAnnotation(value = "programiz") public void method1() ( System.out.println("Test method 1"); ) public static void main(String() args) throws Exception ( Main obj = new Main(); obj.method1(); ) ) 

Output

 Test method 1 

Meta Annotations

Meta-annotations are annotations that are applied to other annotations.

1. @Retention

The @Retention annotation specifies the level up to which the annotation will be available.

Its syntax is:

 @Retention(RetentionPolicy) 

There are 3 types of retention policies:

  • RetentionPolicy.SOURCE - The annotation is available only at the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS - The annotation is available to the compiler at compile-time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME - The annotation is available to the JVM.

For example,

 @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation(… ) 

2. @Documented

By default, custom annotations are not included in the official Java documentation. To include our annotation in the Javadoc documentation, we use the @Documented annotation.

For example,

 @Documented public @interface MyCustomAnnotation(… ) 

3. @Target

We can restrict an annotation to be applied to specific targets using the @Target annotation.

Its syntax is:

 @Target(ElementType) 

The ElementType can have one of the following types:

Element Type Target
ElementType.ANNOTATION_TYPE Annotation type
ElementType.CONSTRUCTOR Constructors
ElementType.FIELD Fields
ElementType.LOCAL_VARIABLE Local variables
ElementType.METHOD Methods
ElementType.PACKAGE Package
ElementType.PARAMETER Parameter
ElementType.TYPE Any element of class

For example,

 @Target(ElementType.METHOD) public @interface MyCustomAnnotation(… ) 

In this example, we have restricted the use of this annotation to methods only.

Note: If the target type is not defined, the annotation can be used for any element.

4. @Inherited

By default, an annotation type cannot be inherited from a superclass. However, if we need to inherit an annotation from a superclass to a subclass, we use the @Inherited annotation.

Its syntax is:

 @Inherited 

For example,

 @Inherited public @interface MyCustomAnnotation (… ) @MyCustomAnnotation public class ParentClass(… ) public class ChildClass extends ParentClass (… ) 

5. @Repeatable

An annotation that has been marked by @Repeatable can be applied multiple times to the same declaration.

 @Repeatable(Universities.class) public @interface University ( String name(); ) 

Giá trị được xác định trong @Repeatablechú thích là chú thích vùng chứa. Chú thích vùng chứa có giá trị biến kiểu mảng của chú thích có thể lặp lại ở trên. Đây Universitieslà loại chú thích có chứa.

 public @interface Universities ( University() value(); ) 

Bây giờ, @Universitychú thích có thể được sử dụng nhiều lần trên cùng một khai báo.

 @University(name = "TU") @University(name = "KU") private String uniName; 

Nếu cần truy xuất dữ liệu chú thích, chúng ta có thể sử dụng API phản chiếu.

Để truy xuất giá trị chú thích, chúng tôi sử dụng getAnnotationsByType()hoặc getAnnotations()phương pháp được xác định trong API phản chiếu.

thú vị bài viết...