"JAVA programming ideas" study notes: Chapter 20 (comment)

Contents
Java programming ideas (a) 1 to 4 chapters: Overview of
Java programming ideas (b) Chapter 5: initialization and cleanup
Java programming ideas (c) Chapter 6: Access
Section (d) of the 7 Java programming ideas: Complex with class
Java programming ideas (e) Chapter 8: polymorphism
Java programming ideas (six) Chapter 9: Interface
Java programming ideas (seven) Chapter 10: internal class
chapter (h) of the 11 Java programming ideas: holding the object
thinking in Java (nine) Chapter 12: abnormal
thinking in Java (x) Chapter 13: string
chapter (XI) of 14 Java programming ideas: type information
(xii) Chapter 15 Java programming ideas: generic
Java programming ideas (13) Chapter 16: arrays
Java programming ideas (xiv) Chapter 17: In-depth study of container
Java programming ideas (xv) Chapter 18: Java I / O system
Java programming ideas (XVI) 19 Chapter: enumeration
Java programming ideas (17) Chapter 20: Notes

Chapter 20 notes

Foreword

  • Annotations Annotation: metadata called a common format introduced JDK5 arranged to provide information for the program.
  • Use the metadata annotation Annotation can write in the program source code, making the code looks simple, but the compiler also provides annotation Annotation of type checking, so during compilation can be ruled out grammatical errors.
  • Notes allows us to by the compiler to test and validate the format, store extra information about the program.
  • Annotations can be used to generate a descriptor file, or even a new class definition, and help alleviate the burden of writing "model" code.

JDK built-in 3 Annotation

In JDK5, built three general purpose annotation Annotation, three built-in annotation java.lang package:

  • @Override: This annotation methods commonly used in the subclass inherits class or implement the interface, the surface of which is covered by subclass the parent class, method signature of the method to be followed in principle cover method: the access control rights than the parent will be able to more stringent class, can not throw more exceptions than the parent class.
  • @Deprecated: This annotation tells the compiler that element is obsolete, that in the current JDK version has a new element instead of the element.
  • @SuppressWarnings: The annotation off compiler warnings inappropriate, i.e., pressing force warning compiler.

 

1. Basic grammar

1.1 Definitions comment

  • Annotation flag (marker annotation): No annotation elements, such as @Test void test () {}
  • Meta-annotation (meta-annotation): often need to use the @ Target, @ Retention and other annotation when declaring annotation, this annotation is called annotated notes (metadata annotation), which is designed to handle the annotation Annotation itself.
@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface Test{}

@Target comment

Indicating the type of program elements for the target applied annotations, and the annotation ElementType enumerated type often used in conjunction, provide ElementType enumeration java program element type declared as follows:

  • ANNOTATION_TYPE: annotation type declaration.
  • CONSTRUCTOR: constructor statement.
  • FIELD: field declarations (including enumeration constants).
  • LOCAL_VARIABLE: local variable declaration.
  • METHOD: the method declaration.
  • PACKAGE: package declaration.
  • PARAMETER: parameters statement.
  • TYPE :: class, interface, or enum declaration.

@Retention comment

The annotation for the annotation indicating the type of comment statements defined in the program period shall retain range, and the annotations often used in conjunction with an enumeration RetentionPolicy. RetentionPolicy enumeration constants defined retention policies annotations in the code

  • CLASS: compiler to notes recorded in the class file, but at runtime JVM not need to keep notes.
  • RUNTIME: comment recording the compiler in the class file, the JVM runtime retained annotations, annotation can be read by reflection.
  • SOURCE: only retained in the source code, the compiler at compile time necessary to discard the note.

2. Write annotation processor

Use annotations when a very important part is to create & use annotation processor. Java provides an external tool apt to parse Java source code package annotated.

In normal use annotations in the annotation elements required for receiving the value set by the program, an example of the normal definition annotation follows:

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface UseCase{

    public int id();

    public String description() default “no description”; //可以定义属性默认值

}

The normal definition annotation Annotation manner similar to the definition of the interface, id, and description is a comment UseCase properties, not methods, annotations can not define the method can only be defined properties. Wherein the description attribute has a default value of "no description", i.e., the program will use the default value if the value is not specified in the description of the use.

 

The above test methods for tracking UseCase annotation instructions annotation above examples are as follows:

public class PasswordUtils{

    @UseCase(id = 47, description = “Passwords must contain at least one numeric”)

    public Boolean validatePassword(String password){

        return (password.mathes(“\\w*\\d\\w*”));

    }

    @UseCase(id = 48)

    public String encryptPassword(Srring password){

        return new StringBuilder(password).reverse().toString();

    }

    @UseCase(id = 49, description = “New passwords can’t equal previously used ones”)

    public Boolean checkForNewPassword(List<String> prevPasswords, String password){

        return !prevPasswords.contains(password);

    }

}

Annotation JDK5 provides the API associated, binding java reflection mechanism may be implemented using a processor Annotation custom annotations (JDK also provides the use of APT, Annotationprocess tool annotations manner, will be explained later), an example of processing said Annotation as follows:

public class UseCaseTracker{

public static void traceUseCases(List<Integer> useCases, Class<?> clazz){

// Get all the specified class method declared

for(Method m : clazz.getDeclaredMethods()){

// Get the specified type of methodological notes

public class UseCaseTracker{  
    public static void traceUseCases(List<Integer> useCases, Class<?> clazz){  
        //获取指定类中所有声明的方法  
        for(Method m : clazz.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 ArrayLis<Integer>();  
        Collections.addAll(useCases, 47, 48, 49, 50);  
        trackUseCases(useCases, PasswordUtils.class);  
    }  
}  

This procedure uses two methods reflections: getDeclaredMethods () and m.getAnnotation (UseCase.class):

  • getDeclaredMethods () method returns the class declaration
  • m.getAnnotation (UseCase.class) Returns the annotation object of the specified type. Without this type of annotations on the annotated method with, null value is returned.

2.1 Annotation annotation elements

Annotation annotation elements only the following data types:

  • All basic types (int, float, boolean, etc.): 8 java basic types, such as int, boolean, etc., if the automatic boxing and unboxing, you can use the corresponding object type of packaging.
  • String
  • Class
  • enum
  • Annotation
  • The above type of array

Apart from these types of the above, if other types of data defined in the annotation, the compiler will be given.

 

2.2 The default value is limited

Note: annotation elements either specify a default value, either assigned by the class to use, if that is not the default, use the class nor the assignment, then annotation elements are not like ordinary class member variables as given default, which must be assigned specify a default value or a display. Examples of the default values ​​as follows:

@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface DefaultValue{  
    public int id() default -1;  
    public String description() default “”;  
}  

2.3 generate an external file

Such technology Enterprise JavaBean, each Bean require a lot of interfaces and deployment to describe the document, these are all boilerplate. However, if we use annotations, you can have all the information stored in the source file in the javaBean. To this end, we need some new annotations to name the name of the database table associated with the definition of Bean, Bean property management as well as columns and SQL types.

@Target(ElementType.TYPE)//该注解只能应用在类上  
@Retention(RetentionPolicy.RUNTIME)  
public @interface DBTable{//指定数据库名称  
    public String name() default “”;  
}  
  
@Target(ElementType.FIELD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface Constraints{//数据库约束  
    boolean primaryKey() default false;  
    boolean allowNull() default true;  
    boolean unique() default false;  
}  
  
@Target(ElementType.FIELD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface SQLString{//String类型数据  
    int value() default 0;  
    String name() default “”;  
    Constraints constraints() default @Constraints;//注解的属性元素也是注解  
}  
  
@Target(ElementType.FIELD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface SQLInteger{//int类型数据  
    String name() default “”;  
    Constraints constraints() default @Constraints;   
}  

 

 

 

Published 222 original articles · won praise 73 · views 960 000 +

Guess you like

Origin blog.csdn.net/cbk861110/article/details/104117378