Annotations are an easier way to add information to our code, and with annotations, we can use some data very conveniently at the right time. The concept of a specific annotation is not expanded, specifically using an example to illustrate the use of custom annotations.
The specific scenario is that we opened a supermarket, the supermarket has an automatic container machine, container machine products have product number, price, product description and precautions, supermarket managers need to sell things in the vending machine in real-time record, through the annotations and then carry out the sale of relevant information records, To achieve this goal, we first affirm an annotation, as follows:
@Target (Elementtype.method) @Retention (retentionpolicy.runtime) public @Interface Product { publicint ID (); Public String Price (); Public String name (); Public default "";}
Then we will design our vending machines:
Public classSelfservice {@Product (id=1,price= "1.00", name= "Apple") Public voidsellapple () {System.out.println ("Apple selled"); } @Product (ID=2,price= "2.0", name= "banana", notict = "eat more easily apparent") Public voidSellbanana () {System.out.println ("Banana selled"); } @Product (ID=3,price= "5.00", name= "Orange") Public voidSellorange () {System.out.println ("Orange selled"); }}
Java Annotation Learning (I. Introduction to annotations, custom annotations)