annotations (also known as metadata) provide a formalized way for us to add information to our code so that we can use it very conveniently at a later point in time.
--------------------------------------------------------------------------------------------------------------- -----------------------------
1. Define Annotations:
Package Com.test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Target (Elementtype.method) @Retention ( retentionpolicy.runtime) Public @interface usecase {public int id ();p ublic String description () default "no description";}
2. In the following class, there are three methods that are annotated as use cases:
Package Com.test;import Java.util.list;public class Passwordutils {@UseCase (id = $, Description = "Passwords must contain At lease one numeric ") Public boolean ValidatePassword (String password) {return password.matches (" \\w*\\d\\w* ");} @UseCase (id = $) public String Encryptpassword (String password) {return new StringBuilder (password). reverse (). toString ();} @UseCase (id = $, Description = "New password can ' t equal previously used ones") Public boolean Checkfornewpassword (list< ; string> prevpasswords, String password) {return!prevpasswords.contains (password);}}
3. Write the Annotation processor:
Package Com.test;import Java.lang.reflect.*;import java.util.*;p ublic class Usecasetracker {public static void Trackusecases (list<integer> usecases, class<?> cl) {for (Method m:cl.getdeclaredmethods ()) {UseCase UC = M.G Etannotation (Usecase.class), if (UC! = null) {System.out.println ("Found use case:" + uc.id () + "" + uc.description ()); UseC Ases.remove (New Integer (Uc.id ()));}} for (int i:usecases) {System.out.println ("warning:missing use case-" + i);}} public static void Main (string[] args) {list<integer> usecases = new arraylist<integer> (); Collections.addall (usecases, N, A,,), Trackusecases (usecases, Passwordutils.class);}}
Output:
Found use case:49 New password can ' t equal previously used ones
Found use case:47 passwords must contain at lease one numeric
Found Use case:48 No description
Warning:missing Use case-50
Java annotations (Getting started)