Defining annotations
Here is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions.
In fact, they compile to class files like any other Java interface:
------------------------------- First define the annotation, similar to an interface --------------------------------------------------------------------
Import java. lang. annotation .*;
@ Target (ElementType. METHOD) // This Is A Metadata Annotation. The definition of the annotation requires a Metadata Annotation.
@ Retention (RetentionPolicy. RUNTIME)
Public @ interface UseCase {// note the writing method here
Public int id ();
Public String description () default "no description ";
}
------------------------------- Use Annotation ----------------------------------------------------------------------------------------------
Import java. util .*;
Public class PasswordUtils {
@ UseCase (id = 47, description =
"Passwords must contain at least one numeric ")
Public boolean validatePassword (String password ){
Return (password. matches ("\ w * \ d \ w *"));
}
@ UseCase (id = 48)
Public String encryptPassword (String password ){
Return new StringBuilder (password). reverse (). toString ();
}
@ UseCase (id = 49, description =
"New passwords can't equal previusly used ones ")
Public boolean checkForNewPassword (
List PrevPasswords, String password ){
Return! PrevPasswords. contains (password );
}
}
----------------------------- Use the reflection mechanism and test the annotation using ---------------------------------------------------------------------
Import java. lang. reflect .*;
Import java. util .*;
Public class UseCaseTracker {
Public static void
TrackUseCases (List UseCases, Class Cl ){
For (Method m: cl. getDeclaredMethods ()){
UseCase uc = m. getAnnotation (UseCase. class );
If (uc! = Null ){
System. out. println ("Found Use Case:" + uc. id () +
"" + Uc. description ());
UseCases. remove (new Integer (uc. id ()));
}
}
For (int I: useCases ){
System. out. println ("Warning: Missing use case-" + I );
}
}
Public static void main (String [] args ){
List UseCases = new ArrayList ();
Collections. addAll (useCases, 47, 48, 49, 50 );
TrackUseCases (useCases, PasswordUtils. class );
}
}
------------------------------------------------------------------ Output result ----------------------------------------------------------------
/* Output:
Found Use Case: 47 Passwords must contain at least one numeric
Found Use Case: 48 no description
Found Use Case: 49 New passwords can't equal previusly used ones
Warning: Missing use case-50