First quote Baidu Encyclopedia of the noun analysis:
Definition: Annotations (Annotation), also called metadata. A description of the code level. It is a feature introduced in JDK1.5 and later versions, with classes, interfaces, and enumerations at the same level. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, and so on, to explain these elements, comments.
Function Classification:
① Writing documents: Generating documents from the metadata identified in the code "generating document DOC Documents"
② Code Analysis: Parsing code with metadata identified in code "using reflection"
③ compile check: The metadata identified in the code allows the compiler to implement the basic compile check "Override"
The following begins the text:
Overview:
As mentioned above, there are several uses of annotations, the first of which is to write a document that will exist in the Javadoc;
The second is Code analysis, which requires the use of reflective APIs to parse annotations;
The third kind is to provide compile-time checks, such as deprecated, which generate a warning message when compiling.
For a few examples:
1, the following example, the annotations use the @documented annotation, which means that our annotations will appear in the Javadoc generated document, the other @retention of the use of the following will be said
Package Com.ruby;import Java.lang.annotation.documented;import Java.lang.annotation.retention;import Java.lang.annotation.RetentionPolicy, @Documented @retention (retentionpolicy.source) public @interface classpreamble { String author ();}
Use:
@ClassPreamble ( author = "Ruby") public class Main ...
2, Code Analysis (we have a poor simulation of spring boot routing annotations)
Code directory Structure:
requestmapping Annotation Definitions:
Package Com.ruby.annotation;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Retention (retentionpolicy.runtime) @ Target (elementtype.method) public @interface requestmapping { String value () default "/";}
Home controller definition:
Package Com.ruby.controller;import Com.ruby.annotation.requestmapping;public class Home { @RequestMapping ("Test ") Public void HelloWorld () { System.out.println (" HelloWorld! ");} }
Methods of use (naming is not too canonical, test is typically used for testing file naming): The key is to parse the code in the main method through reflection, the other two methods are just tool methods (to get all the classes under the package)
Package Com.ruby.test;import Com.ruby.annotation.requestmapping;import Java.io.file;import java.io.IOException; Import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.net.URL;import Java.util.arraylist;import Java.util.enumeration;import Java.util.list;public class TestHome {public static void main ( String[] args) throws ClassNotFoundException, IOException, Instantiationexception, Illegalaccessexception, invocationtargetexception{String route = "Test"; class[] classes = getclasses ("Com.ruby.controller"); for (Class cls:classes) {method[] methods = Cls.getmethods (); for (Method method:methods) {requestmapping requestmapping = method.getannotation (Requestmapping.class); if (requestmapping! = null) {String mapping = Requestmapping.value (); if (Mapping.equals (route)) {Method.invoke (cls.newinstance ()); }}}}}/** * Scans All classes accessible from the context class loader whic H belong to the given package and subpackages. * * @param packagename the base package * @return The classes * @throws classnotfoundexception * @throws I Oexception */private static class[] Getclasses (String packagename) throws ClassNotFoundException, Ioexc eption {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); Assert classLoader! = null; String path = Packagename.replace ('. ', '/'); enumeration<url> resources = classloader.getresources (path); List<file> dirs = new arraylist<file> (); while (Resources.hasmoreelements ()) {URL resource = resources.nextelement (); Dirs.add (New File (Resource.getfile ())); } arraylist<class> classes = new arraylist<class> (); for (File directory:dirs) { Classes.addall (findclasses (directory, packagename)); } return Classes.toarray (New Class[classes.size ())); }/** * Recursive method used to find all classes in a given directory and Subdirs. * * @param directory The base directory * @param packagename the package name for classes found inside the base Directory * @return The classes * @throws ClassNotFoundException */private static list<class> FINDCL Asses (File directory, String PackageName) throws ClassNotFoundException {list<class> classes = new ArrayList <Class> (); if (!directory.exists ()) {return classes; } file[] files = directory.listfiles (); for (File file:files) {if (File.isdirectory ()) {Assert!file.getname (). Contains ("."); Classes.addall (findclasses (file, PackageName + "." + File.getname ())); } else if (File.getname (). EndsWith (". Class")) { Classes.add (Class.forName (PackageName + '. ' + file.getname (). substring (0, File.getname (). Length ()-6)); }} return classes; }}
3, compile-time check: such as @suppresswarnings, if some obsolete method call will have a warning message, you can use the @suppresswarnings annotation: @SuppressWarnings ("deprecation"), This will not generate a warning message when compiling.
Annotation definition
Annotation definition method is similar to the interface definition (example above), just before the interface keyword more than a @ symbol, the annotation definition can also have other annotations (detailed below), the annotation body inside the elements of the basic format are consistent, type name + variable name + brackets + default xxx; The supply of the default value is optional. Types can be normal types, or they can be classes, exceptions, and so on.
Next to the hair map, it is more clear:
Annotation classification:
1, general annotations, such as: @Deprecated, @Override, @SuppressWarnings, @SafeVarargs, etc.
2, annotations other annotations (more awkward): Remember the focus, the more critical is @retention, @Target
Other do not say, first hair diagram, look at the picture is clear:
First of all, @retention, this is very important, if we want to use the defined annotations at runtime, we must not write the wrong, the default is not to the runtime still exist
How to use: Use at the annotation definition:
@Retention (retentionpolicy.source) public @interface classpreamble { String author ();}
There are three optional options:(Default is Retentionpolicy.class)
1, Retentionpolicy.source, if the use of this option, our annotations will only exist in the source code, after the compilation is not, we look at the compiled class file, we will find that the annotations no longer exist. However, if we do not write @retention, the compiled class file will also have this annotation, because the default is Retentionpolicy.class.
2, Retentionpolicy.class (default), using this option, our annotations will exist in the source code and CLASS file
Java Annotations Detailed