Get the App
SLTechnology News&Howtos  ›  Development  › 

What are repeated annotations in Java 8?

Shulou Source: shulou.com Published: 2022-06-03 11:14:03 09月25日 Update

In order to solve the problem of repeated annotations in Java 8, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

What is repetitive comment

Allow the same annotation to be used multiple times in the same declaration type (class, property, or method)

A simple example.

There were solutions for reusing annotations before java 8, but they were not very readable, such as the following code:

Public @ interface Authority {String role ();} public @ interface Authorities {Authority [] value ();} public class RepeatAnnotationUseOldVersion {@ Authorities ({@ Authority (role= "Admin"), @ Authority (role= "Manager")) public void doSomeThing () {}}

Duplicate annotations are stored by another annotation, and when in use, duplicate annotations are extended with stored annotations Authorities. Let's take a look at what happens in java 8:

@ Repeatable (Authorities.class) public @ interface Authority {String role ();} public @ interface Authorities {Authority [] value ();} public class RepeatAnnotationUseNewVersion {@ Authority (role= "Admin") @ Authority (role= "Manager") public void doSomeThing () {}}

The difference is that when you create a repeating annotation Authority, add @ Repeatable to point to the storage annotation Authorities. When you use it, you can reuse the Authority annotation directly. As can be seen from the above examples, the method in java 8 is more suitable for conventional thinking and is more readable.

Summary

JEP120 doesn't have much content, it's a small feature, just to improve the readability of the code. This time java 8 has made two improvements to the annotations (JEP 104 JEP120). It is believed that annotations will be used more frequently than before.

This is the answer to the question about repeated comments in Java 8. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Comments readability questions storage code examples practices content methods time more help solutions different easy frequent easy local guys buddies Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft MariaDB Xiaomi macOS