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:
[Java]View PlainCopy
- 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 ();
- Public String Description () default "no description";
- }
2. In the following class, there are three methods that are annotated as use cases:
[Java]View PlainCopy
- 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:
[Java]View PlainCopy
- Package com.test;
- Import java.lang.reflect.*;
- Import java.util.*;
- Public class Usecasetracker {
- public static void trackusecases (list<integer> 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<integer> usecases = new arraylist<integer> ();
- Collections.addall (usecases, 50);
- 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
-
Top
-
1
Java Annotations @interface (Getting started) (GO)