I. Overview of annotations
1, learning annotations can read other people's code, especially the framework-related code2, make your own programming more concise, more clear code3, let others thought highly one eye, will use the custom annotation to solve the problem 4. Concept: Java provides a way and method of any metadata associated with any information in an element of the original program Second, common annotations in Java Annotation 1. JDK comes with annotations@Override@Deprecated means that the method is obsolete, adding an underscore to the method ,@Suppvisewarnings means ignore warning2. Common third-party annotationsSpring: @Autowired@Service@RepositoryMysbatis: @InsertProvider@updateProvider@Options Iii. Classification of annotations1, according to the operating mechanism of:Source Annotations: Annotations only exist in the source code, compiled into a. class file will not exist. Compile-time annotations: annotations exist in both the source code and the. class fileRuntime Annotations: Also works at run time, even annotations that affect the running logic2, according to the source points:Notes for JDKthird-party annotationsCustom Annotations3. Meta-Annotations: annotationsIv. Custom Annotations1. Syntax requirements for custom annotations The member type is limited, including the original data type, String,class,annotation,enumerationIf the annotation has only one member, the member name must be named value (), and the member name and assignment number (=) can be Ray Hu when used.annotations can have no members, and annotations without a process member are called identity annotations2, Yuan annotationScope of @Target annotations: Construct method, domain, local variable life, method, package, parameter, class, interface@Retention The life cycle of annotations: SOURCE, CLASS, RUNTIME@Inherited allow child annotations to inherit from it@Documented information that contains annotations when generating Javadoc3. Using custom annotationssyntax for using annotations:@< Annotation Name > (< member name 1>=< member value 1>,<>=<>,...... ) 4. Analytical AnnotationsTo obtain runtime annotation information on a class, function, or member by reflection, thus realizing the logic of dynamic control program running
//1.使用类加载器加载类
Class c =Class.forName("要解析的类的全名");
//2.找到类上面的注解
boolean isExist = c.isAnnotationPresent(xxx.class);//xxx表示你要解析的注解的类名
if(isExist){
//3.拿到注解实例
xxx d =(xxx)c.getAnnotation(xxx.class);
System.out.println(d.value());
}
//4.找到方法上的注解
Method[] ms = c.getMethod();
for(Method m:ms){
boolean isMExist = m.isAnnotationPresent(xxx.class);
if(isMExist){
xxx d =(xxx)m.getAnnotation(xxx.class);
System.out.println(d.value());
}
//另一种解析方法
for(Method m:ms){
Annotation[] as = m.getAnnotation();
for(Annotation a: as){
if(a instanceOf xxx);
xxx d =(xxx)a;
System.out.println(d.value());
}
}
}
v. Use custom annotations to solve problems in real -world projects If you develop a hibernate
From for notes (Wiz)
Full parsing of Java annotations