Annotations are one of the most important language changes introduced into Java SE5. It provides 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. Today we begin to learn the knowledge of annotations in Java.
Introduction to Java Annotations
Java has built-in three standard annotations, as well as four types of meta annotations. Meta annotations are responsible for annotating other annotations.
Standard NOTE: @Override, @Deprecated, @Suppresswarnings.
Meta notes: @Target, @Retention, @Documented, @Inherited.
Use cases for Java annotations
The project structure of the test is as follows:
First, define the annotations:
PackageCom.linux.huhx.anno;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/*** @Author huhx * @Date: 2017/9/17 20:07 * Define annotations:*/@Target (Elementtype.method) @Retention (retentionpolicy.runtime) Public@InterfaceHuhxtest { Public intID (); PublicString description ()default"No description";}
Second, write the test class to be annotated
PackageCom.linux.huhx.anno;Importjava.util.List;/*** @Author huhx * @Date: 2017/9/17 20:13*/ Public classpasswordutils {@HuhxTest (id= Description = "Password must contain at least one numeric") Public BooleanValidatePassword (String password) {returnPassword.matches ("\\w*\\d\\w*"); } @HuhxTest (ID= 48) Publicstring Encryptpassword (string password) {return NewStringBuilder (password). reverse (). toString (); } @HuhxTest (ID= $, Description = "New passrod can ' t equal previously used ones") Public BooleanCheckfornewpassword (list<string>prevpasswords, String password) { return!prevpasswords.contains (password); }}
Third, write the note processor
PackageCom.linux.huhx.anno;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;/*** @Author huhx * @Date: 2017/9/17 20:12*/ Public classUsecasetracker { Public Static voidTrackusecases (list<integer> usecases, class<?>cl) { for(Method m:cl.getdeclaredmethods ()) {huhxtest test= M.getannotation (huhxtest.class); if(Test! =NULL) {System.out.println ("Found use case:" + test.id () + "," +test.description ()); Usecases.remove (NewInteger (Test.id ())); } } for(inti:usecases) {System.out.println ("Warning:missing use case" +i); } } Public Static voidMain (string[] args) {List<Integer> usecases =NewArraylist<>(); Collections.addall (usecases,47, 48, 49, 50); Trackusecases (Usecases, passwordutils.class); }}
The results of the operation are as follows:
Case the new Passrod can't equal previously used onescase case
Friendship Link
Java Basics----Use of >java annotations (i)