Java annotation comprehension and Examples

Source: Internet
Author: User

Java annotation comprehension and Examples
I. Introduction when using eclipse auto-completion tools, you must have encountered the word "@ Override" during method rewriting. Then I was wondering what it was. After deletion, I found that the program could run without affecting the program itself, like a red comment. However, if it is a comment, why not just comment it out? This is today's main character-annotation. Since jdk1.5, annotations and reflection have been introduced, and they have become a part of development and are widely used. Some people think that annotations should also be part of reflection, without reflection, and annotations cannot be used normally, but reflection is still normal without annotations. However, these are not important points. 2. Description: Annotation is also called metadata to describe data. It can be declared before packages, classes, fields, methods, and local variables to describe these elements. Its functions are as follows: 1. write: generate a document using the data identified in the Code; 2. code Analysis: analyze the code using the data identified in the Code (Using Reflection) 3. compilation check: the metadata identified in the Code enables the compiler to implement basic compilation check (Override) 3. annotation syntax and classification: (JDK) annotation Syntax: @ + annotation type A: Three standard Annotations: @ Override: indicates that the current method definition will overwrite the method of the parent class; @ Deprecated: the element compiler that uses annotation for it will issue a warning because annotation @ Deprecated is a code that is not in favor of use and is discarded. @ SuppressWarnings: Disable improper compiler warning information B: Four meta annotations (other annotations): @ Docmented: whether the annotation is included in JavaDoc @ Retention: the level at which the annotation information is saved. Optional RetentionPolicy parameter {SOURCE: annotation will be discarded by the compiler. It does not make any sense after compilation (@ Override, @ SuppressWarnings all belong to this type of annotation) CLASS: annotation is available in the class file, but it is discarded by the VM (the default annotation method). RUNTIME: the VM retains the annotation during running, so the annotation information can be read through the reflection mechanism. (This method is usually used for custom annotations)} @ Target: Where is the annotation used. Optional ElementType PARAMETER {CONSTRUCTOR: FIELD of the CONSTRUCTOR: FIELD Declaration includes the enum instance LOCAL_VARIABLE: local variable declaration METHOD: METHOD declaration PACKAGE: PACKAGE declaration PARAMETER: PARAMETER declaration TYPE: class, interface, annotation type, enum declaration} @ Inherited: whether to allow subclass to inherit the annotation. 4. Write a custom annotation for instance 1.

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Test { }

 

Note: Except for the @ symbol, the annotation is very similar to an interface. Meta annotation is required for defining annotations. In the annotation, some elements are usually used to indicate some values. The annotation element looks like an interface method. The only difference is that the annotation without elements by default can be set for it. The above @ Test is a tag annotation. The available types of annotations include the following: all basic types, String, Class, enum, Annotation, and arrays of the above types. Elements cannot have uncertain values, that is, they either have default values or provide element values when using annotations. The element cannot use null as the default value. Note when there is only one element and the element name is value, you can omit "value =" when using the annotation and directly write the required value. Instance 2
// Custom annotation @ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) public @ interface User {public String id (); public String description () default "description ";}

 

// Use the above annotation public class Login_Token {@ User (id = 1, description = "give me your password! ") Public boolean PasswdValid (String passwd) {boolea flag = true ;... return flag;} @ user (id = 2) public String nextPasswd (String passwd ){...}}

 

Instance 3:
// Custom annotation @ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) {public @ interface cola {public enum Priority {LOW, HIGH} String author () deafault "jia"; Priority priority () deafault Priority. LOW ;}// use the annotation @ cola (priority = cola. priority. HIGH, author = "cola") public void method (){...}

 

Instance 4
// There is only one value in the annotation. You can directly name it "value" without specifying the attribute name. @ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) public @ interface cola {String value () ;}// use the preceding annotation to omit "value =" @ cola ("jia") public void method () {...}

 

The following fully copy network resources 5. annotation Use Case annotation functions are very powerful. Spring and Hebernate frameworks use annotation functions extensively in logs and validity. Annotations can be used in the place where the mark interface is used. The difference is that the mark interface is used to define the complete class, but you can define comments for a single method, such as whether to expose a method as a service. Many new annotations are introduced in the latest servlet3.0, especially those related to servlet security. HandlesTypes-This annotation is used to indicate a group of application classes passed to ServletContainerInitializer. HttpConstraint-This annotation represents the security constraints of all HTTP method application requests. It is different from the HTTP methodconstraint security constraint defined in the ServletSecurity annotation. HttpMethodConstraint-specifies the security constraints for different types of requests, which is different from the annotations describing the HTTP protocol method types in the ServletSecurity annotation. MultipartConfig-the annotation is marked on the Servlet, indicating that the MIME type of the request to be processed by the Servlet is multipart/form-data. ServletSecurity the annotation is marked on the Servlet inheritance class, And the HTTP request is forced to follow the security constraints. WebFilter-This annotation is used to declare a Server filter. WebInitParam-This annotation is used to declare initialization parameters in Servlet or filter. It is usually used with @ WebServlet or @ WebFilter. WebListener-This annotation is a listener for different types of event Declaration in the context of Web applications. WebServlet-This annotation is used to declare the configuration of a Servlet. The application framework and annotations are now the last part of the article. The application framework, known as the ADF, is developed by Oracle to create an Oracle Integrated application. We already know the advantages and disadvantages of annotations and how to write custom annotations. But what part of the annotation should we apply to the ADF? Does the ADF provide some simple annotations? A good problem is that there are some restrictions on the extensive use of annotations in the ADF. The application frameworks mentioned earlier, such as Spring and Hibernate, use AOP (side-Oriented Programming ). In AOP, the Framework provides a mechanism to inject code into event preprocessing and subsequent processing. For example, you have a hook to add code before and after method execution, so you can write your user code in these places. No AOP is used for the ADF. If we have any annotated use cases available, we may need to implement them through inheritance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.