Java custom annotation

I. Overview
After jdk5, a feature is provided, which is at the same level as a class and an interface. An
annotation is essentially an interface. An interface can have constants and abstract methods. The abstract methods are called annotation attributes in the annotation.
Example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessTokenVerify {
	AccessTokenVerifyEnum value() default AccessTokenVerifyEnum.APP;
}
public enum AccessTokenVerifyEnum {
    APP("app"),
    WEB("web");
    private String message;
    AccessTokenVerifyEnum(String message) {
        this.message = message;
    }
}
Second, the annotations provided by jdk
@Override describes the override of the method @SuppressWarnings suppresses warnings, there are many values, all suppresses all warnings @Deprecated marks obsolete
        

3. Types of annotation attributes
String
Class
Annotation
Enum
and one-dimensional arrays of the above types
Note : If the annotation has an attribute, it must be assigned when using the annotation (unless the annotation attribute has a default value)
4. Annotation format
@interface annotation name {attribute}
assignment format:
@annotation name (attribute name=attribute value)
If the annotation type is an array and there is only one value, there are two ways to write
it Method 1:
attribute name = { value}
Method 2 :
Attribute name=Attribute value
If the attribute name is value, and only need to assign value to this value attribute, value can be omitted
5. Meta Annotation
The annotation @Retention defined on the annotation specifies  to what stage the annotation is retained. The three enumeration values ​​with the value of RetentionPolicy are as follows RUNTIME is reserved in the file : @Target is reserved for all phases. The enumeration value whose value is ElementType is as follows . TYPE: acts on classes and interfaces. METHOD: acts on methods FIELD: acts on fields.









6. The role of annotations
Compilation check
Alternate configuration file
Define annotations (meta-annotations: annotations on annotations)
Analyze code (use reflection)
7. Annotation case
Case 1 : Use annotation reflection to optimize BaseDao ( to be
continued) Case 2: Use  annotations to
develop JDBC classes Annotation property String driverClass() default "com.mysql.jdbc.Driver"; String url(); String username() default "root"; String password(); ② Provide a getConnection in the jdbcutils tool class, add above the method An annotation @JDBCInfo(...) What  the getConnection method needs to do: get the four attribute values ​​on the annotation, get the bytecode file , get the annotation on the method, get the value of the annotation ③ When running, you can get a connection through getConnection















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324785686&siteId=291194637