How does the annotations (Annotation) in Java Java work?

Source: Internet
Author: User

How does the annotations in Java work?

Since the introduction of annotations in the Java5.0 version, it has become a very important part of the Java platform. In the development process, we also often see annotations such as @override, @Deprecated in the application Code. In this article, I'm going to tell you exactly what annotations are, why you should introduce annotations, how annotations work, How to write custom annotations (through examples), where you can use annotations and the latest annotations and ADF (application development framework). This will take some time, so prepare yourself a cup of coffee and let's go into the annotated world.

What is an annotation?

The annotation can be described in one word, that is, metadata, a data that describes the Data. so, It can be said that the annotation is the source code Metadata. For example, the following code:

1234 @OverridepublicString toString() {    return"This is String Representation of current object.";}

In the code above, I rewrote the toString() method and used @Override Annotations. however, even if I do not use the @Override注解标记代码,程序也能够正常执行。那么,该注解表示什么?这么写有什么好处吗?事实上, @Override 告诉编译器这个方法是一个重写方法(描述方法的元数据),如果父类中不存在该方法,编译器便会报错,提示该方法没有重写父类中的方法。如果我不小心拼写错误,例如将toString() written toStrring(){double r} , and I do not use @Override annotations, the program can still compile and Run. But the results will be very different from what I expected. Now we understand what annotations are and use annotations to help you read the Program.

Annotation is a special modifier applied to classes, methods, parameters, variables, constructors, and package Declarations. It is a tool chosen by the JSR-175 standard to describe Metadata.

Why should I introduce annotations?

Before using annotation (even after use), XML is widely used to describe Metadata. I don't know when to start some app developers and architects find XML maintenance getting Worse. They want to use something that is tightly coupled to the code, rather than a code description that is loosely coupled (or, in some cases, completely detached) from the code, as in Xml. If you search for "XML vs. annotations" in google, you'll see a lot of debate on this Issue. The most interesting thing is that the XML configuration is actually introduced for separating code and Configuration. These two ideas may make you wonder, both of which seem to form a cycle, but each has its pros and cons. Let's use an example to understand the difference between the Two.

If you want to set a number of constants or parameters for your app, in this case, XML is a good choice because it doesn't connect to specific Code. If you want to declare a method as a service, it would be better to use annotation, because in this case the annotations and methods need to be tightly coupled, and developers must recognize This.

Another important factor is that annotation defines a standard way to describe Metadata. Until then, developers typically use their own way to define Metadata. For example, use tag interfaces, annotations, transient keywords, and so On. Each programmer defines metadata in its own way, rather than as a standard way of Annotation.

currently, many frameworks combine XML with annotation two ways to balance the pros and cons of Both.

How does the annotation work? How to write a custom annotation?

Before you tell this section, we recommend that you first download the sample code annotationssample.zip for Annotation. After downloading it in the IDE you are accustomed to using, this code will help you better understand the annotation mechanism.

Writing annotation is very simple, you can compare the definition of annotation with the definition of an interface. Let's take a look at two Examples: one is the standard annotation @override and the other is the user-defined annotation @todo.

1234 @Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public@interfaceOverride {}

For @override comments You may have some questions about it, and it doesn't do anything, so how does it check that there is a function with the same name in the parent class? of course, Don't be surprised, I'm teasing you. The definition of @Override annotations is more than just a bit of code. This part is important, and I have to repeat it again:annotations is only metadata and is not related to business Logic. It's a little difficult to understand, but that's it. If annotations does not contain business logic, then someone must implement the LOGIC. Metadata of the user to do this thing. Annotations only provides information about the attributes (class/method/package/domain) that it defines. Annotations users (also Some code) to read this information and implement the necessary logic.

When we use Java's callout annotations (for example, @override), The JVM is a user and it works at the bytecode Level. To this point, the application developer cannot control or use the custom Annotations. So let's explain how to write a custom annotations.

Let's go through the main points of writing custom annotations one by One. In the example above, you see some annotations applied to the Annotations.

The j2se5.0 version provides four types of meta-annotations in java.lang.annotation, specifically annotated with other annotations:

@Documented –注解是否将包含在JavaDoc中
@Retention –什么时候使用该注解
@Target? –注解用于什么地方
@Inherited – 是否允许子类继承该注解

@Documented– A simple annotations markup annotation that indicates whether to add annotation information to a Java Document.

@Retention– Defines the life cycle of the Annotation.

Retentionpolicy.source – discarded during the compile Phase. These annotations no longer have any meaning after compilation, so they do not write to Bytecode. @Override, @SuppressWarnings all belong to this kind of annotation.

Retentionpolicy.class – Discarded when the class is Loaded. Useful in the processing of bytecode Files. Annotations are used this way by Default.

Retentionpolicy.runtime– it is never discarded and the runtime retains the annotation, so you can use the reflection mechanism to read information about the Annotation. Our custom annotations are typically used this way.

@Target – Indicates where the note is Used. If not explicitly stated, the annotations can be placed Anywhere. The following are some of the available Parameters. Note that the attribute annotations are compatible, and if you want to add annotations to all 7 attributes, just exclude an attribute, then you need to define the target to include all the Attributes.

ElementType.TYPE:用于描述类、接口或enum声明
ElementType.FIELD:用于描述实例变量
ElementType.METHOD
ElementType.PARAMETER
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE 另一个注释
ElementType.PACKAGE 用于记录java文件的package信息

@Inherited – Define the relationship of this comment and subclass

so, What exactly is the inner definition of the annotation? Annotations only supports basic types, string, and enumeration Types. All attributes in the note are defined as methods and allow default values to be Provided.

123456789 @Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@interface Todo {public enum Priority {LOW, MEDIUM, HIGH}public enum Status {STARTED, NOT_STARTED}String author() default "Yash";Priority priority() default Priority.LOW;Status status() default Status.NOT_STARTED;}

The following example shows how to use the above Annotations.

12345 @Todo(priority = Todo.Priority.MEDIUM, author = "Yashwant", status = Todo.Status.STARTED)publicvoidincompleteMethod1() {//Some business logic is written//But it’s not complete yet}

If there is only one attribute in the annotation, you can name it directly as "value" and use it without having to label the property Name.

123456 @interfaceAuthor{String value();}@Author("Yashwant")public voidsomeMethod() {}

But so far everything looks good. We define our own annotations and apply them to the methods of business Logic. Now we need to write a user program that calls our Annotations. Here we need to use the reflection Mechanism. If you are familiar with reflection code, you know that reflection can provide class names, methods, and instance variable Objects. All of these objects have Getannotation () This method is used to return the annotation Information. We need to convert this object to our custom annotations (after using the instanceof () check), and we can invoke the method inside the custom Comment. Take a look at the following example code, using the above annotations:

12345678910 Class businessLogicClass = BusinessLogic.class;for(Method method : businessLogicClass.getMethods()) {Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);if(todoAnnotation != null) {System.out.println(" Method Name : " + method.getName());System.out.println(" Author : " + todoAnnotation.author());System.out.println(" Priority : " + todoAnnotation.priority());System.out.println(" Status : " + todoAnnotation.status());}}
Annotation Use Cases

Annotations are powerful, and spring and hebernate these frameworks use annotation functionality extensively in log and Effectivity. Annotations can be applied where the labeled interface is Used. The difference is that the tag interface is used to define the complete class, but you can define annotations for a single method, such as whether a method is exposed as a service.

Many new annotations have been introduced in the latest servlet3.0, especially those related to servlet Security.

handlestypes – This annotation is used to represent a set of application classes passed to Servletcontainerinitializer.

Httpconstraint – this annotation represents the security constraints of the application request for all HTTP methods, and differs from the Httpmethodconstraint security constraints defined in the Servletsecurity Annotation.

Httpmethodconstraint – Indicates the security constraints for different types of requests, and differs from the annotations that describe the HTTP protocol method type in the Servletsecurity Annotation.

Multipartconfig – The note is labeled above the servlet, indicating that the MIME type of the request that the servlet wishes to process is Multipart/form-data.

servletsecurity This annotation is labeled on the servlet inheriting class, forcing the HTTP protocol request to follow security Constraints.

Webfilter – This annotation is used to declare a server filter;

Webinitparam – This annotation is used to declare initialization parameters in a servlet or filter, usually in conjunction with @WebServlet or @WebFilter.

Weblistener – This annotation is a different type of event declaration listener in the context of the Web Application.

Webservlet – This annotation is used to declare the configuration of a servlet.

ADF (application Framework) and annotations

Now we're going to start talking about the last part of the Article. The application framework (application development framework), known as adf, is developed by Oracle to create Oracle converged Applications. We already know the pros and cons of annotations and how to write custom annotations, but what part of the ADF should we apply annotations to? Does the ADF provide some simple annotations? Good question, There are some restrictions on the use of annotations in the Adf. Previously mentioned application frameworks such as spring and hibernate use AOP (side-facing programming aspect-oriented programming). In aop, the framework provides a mechanism for injecting code into the preprocessing and subsequent processing of events. For example: you have a hook to add code before and after the method executes, so you can write your user code in these Places. ADF does not use Aop. If we have any annotated use cases available, we may need to implement them in an inherited way.

Question Connection: How annotations in Java work

SOURCE Connection: How Annotations work in Java

How does the annotations (Annotation) in Java Java work?

Related Article

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.