The working principle of annotations in Java _java

Source: Internet
Author: User
Tags aop reflection

Since the Java5.0 version introduced annotations, it has become a very important part of the Java platform. In the development process, we also often see in the application code such as @override, @Deprecated such annotations. In this article, I'll tell you exactly what annotations are, why they are introduced, how annotations work, how to write custom annotations (by example), and when to use annotations and the latest annotations and ADF (Application Development framework). It will take some time, so prepare a cup of coffee for yourself and let us enter the world of annotations.

What is annotation?

A word can be used to describe annotations, that is, metadata, a data that describes the data. So, it can be said that the annotation is the source code of the metadata. For example, the following code:

@Override public
String toString () {return ' This is string representation ' of current
  object. ';
}

In the code above, I rewrote the ToString () method and used the @override annotation. However, even if I do not use the @override annotation tag code, the program can execute normally. So, what does the annotation say? What's the benefit of this writing? In fact, @Override tell the compiler that this method is an overriding method (describing the metadata of the method) and that if the method does not exist in the parent class, the compiler will complain that the method does not override the method in the parent class. If I accidentally misspelled, for example, to write ToString () as tostrring () {double R}, and I did not use the @override annotation, the program can still compile and run. But the results will be very different from what I expected. Now that we know what annotations are, and using annotations helps to read the program.

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

Why should I introduce annotations?

XML is widely used to describe metadata before using annotation (even after use). I don't know when to start some application developers and architects found that the maintenance of XML was getting worse. They want to use something that is tightly coupled to the code, rather than code descriptions like XML and code that is loosely coupled (in some cases, even completely detached). If you search for "XML vs. Annotations" in Google, you will see a lot of debate about this issue. The most interesting thing is that XML configuration is actually introduced to separate code and configuration. These two views may be confusing, and the view seems to form a cycle, but each has its pros and cons. Here's an example to understand the difference between the two.

If you want to set a lot of constants or parameters for the application, in this case, XML is a good choice because it is not connected to a particular 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 the developer must be aware of that.

Another important factor is that annotation defines a standard way to describe metadata. Before that, developers typically define metadata in their own way. For example, use tag interfaces, annotations, transient keywords, and so on. Each programmer defines metadata in its own way, unlike the way annotation this standard.

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 telling this part, it is recommended that you first download the annotation sample code annotationssample.zip. After downloading it in the IDE you used to use, this code will help you to better understand the annotation mechanism.

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

@Target (Elementtype.method)
@Retention (retentionpolicy.source) public
@interface Override {
}

You may have some questions about the @override annotation, it doesn't do anything, 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 little code. This part is important, and I have to repeat it again:annotations is only metadata and has nothing to do with business logic. It's a little difficult to understand, but that's it. If annotations does not contain business logic, then someone has to implement the logic. Meta data users to do this thing. Annotations only provides information about the attributes it defines (class/method/package/domain). Annotations users (as well as some code) to read this information and implement the necessary logic.

When we use the Java annotation annotations (for example, @override), the JVM is a user, and it works at the byte-code level. Here, application developers cannot control or use custom annotations. So, let's explain how to write custom annotations.

Let's go through the main points of writing a custom annotations individually. In the example above, you see that some annotations are applied to annotations.

The j2se5.0 version provides four meta annotations in Java.lang.annotation, which specifically annotate other annotations:

    • @Documented – Annotations will be included in Javadoc
    • @Retention – When to use this annotation
    • @Target? – Where annotations are used
    • @Inherited – Allow subclasses to inherit the annotation

@Documented– A simple annotations markup annotation that indicates whether the annotation information is added to the Java document.

@Retention– Defines the life cycle of the annotation.

Retentionpolicy.source – discarded at compile time. These annotations no longer have any meaning after compilation ends, so they are not written to byte code. @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 Use this method by default.

Retentionpolicy.runtime– is never discarded, and the runtime retains the annotation, so you can use the reflection mechanism to read the annotation's information. Our custom annotations are usually used in this way.

@Target – Indicates where the annotation is used. If it is not clearly stated, the annotation can be placed anywhere. The following are some of the available parameters. Note that the annotation of the attribute is compatible, and if you want to add annotations to all 7 attributes and exclude only one attribute, then you need to include all the attributes in the definition target.

    • Elementtype.type: Used to describe a class, interface, or enum declaration
    • Elementtype.field: Used to describe instance variables
    • Elementtype.method
    • Elementtype.parameter
    • Elementtype.constructor
    • Elementtype.local_variable
    • Elementtype.annotation_type another comment
    • Elementtype.package used to record PACKAGE information for Java files

@Inherited – Define the relationship between the annotation and the subclass

So how does the interior of the annotation actually define it? Annotations only supports base types, string, and enumeration types. All attributes in the annotation are defined as methods and allow default values to be provided.

@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 annotations above.

@Todo (priority = Todo.Priority.MEDIUM, author = "Yashwant", status = Todo.Status.STARTED) public
void IncompleteMethod1 () {
//some business logic is written
//but It's not complete yet
}

If there is only one attribute in the annotation, it can be named "value" without any further indication of the property name.

@interface author{
String value ();
}
@Author ("Yashwant") public
void SomeMethod () {
}

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

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 case

Annotations are powerful, and spring and hebernate these frameworks use the annotation feature heavily in logging and validation. Annotations can be applied where the markup interface is used. The difference is that the markup interface is used to define the complete class, but you can define a comment for a single method, such as whether to expose a method 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 – The annotation represents the security constraint for the application request of all HTTP methods, and is different from the HTTPMETHODCONSTRAINT security constraint defined in the servletsecurity annotation.

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

Multipartconfig – The note is annotated above the servlet, indicating that the MIME type of the request that the servlet expects to handle is multipart/form-data.

servletsecurity The annotation is marked above the servlet inheritance class, forcing the HTTP protocol request to comply with security constraints.

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

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

Weblistener – The annotation is a listener for different types of event declarations 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, called the ADF, is developed by Oracle to create Oracle Fusion applications. We've learned the pros and cons of annotations and how to write custom annotations, but what part of the ADF should we apply the annotations to? Does the ADF provide some simple annotations? Good question, there are certain limitations to using annotations heavily in the ADF. Previously mentioned application frameworks such as spring and hibernate use AOP (side-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. The ADF does not use AOP. If we have any annotated use cases available, we may need to implement them in an inherited way.

I hope you like this article, to help you better understand the meaning of annotations!

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.