Part of Java programmers do not know in the comments in the end is how it works?

Author: Xiao people

Foreword

Since the introduction of notes Java5.0 version, it becomes a very important part of the Java platform. The development process, we often see in the application code so that comments such as @ Override, @ Deprecated.

In this article, I will tell you what is in the end notes, why should the introduction of notes, notes how it works, how to write a custom annotation (by way of example), under what circumstances you can use annotations and the latest comments and ADF (Application Development Framework). It will only take a little time, so be prepared for himself a cup of coffee, let's enter the world annotate it.

What is a comment?

Notes can be described in one word, that is, metadata, that is, a description of the data. So, we can say that the source metadata annotation code. For example, the following code:

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

The above code, I rewrite the toString () method and the use of @Override comment. But, even if I do not use @Override annotation markup code, the program can also be executed properly. br /> So, what notes represent? What are the benefits so write it? In fact, @ Override this method is to tell the compiler (metadata describing the method of) a rewrite method, if the method does not exist in the parent class, the compiler will error, suggesting that the method does not override the parent class method.
If I accidentally misspelled, for example, the toString () written toStrring () {double r}, and I do not use @Override notes that the program was still able to compile and run. However, operating results and I expect will be very different. Now that we know what is annotation, and using annotations help readers.
Annotation is applied to a class, method, parameters, variables, and packet constructor declaration special modifiers. It is a choice by the JSR-175 standard describes a tool for metadata.

Why introduce annotations?

Before using the Annotation (even after use), XML is widely used to describe metadata. I do not know when to start some applications developers and architects found XML maintenance are going bad.
They want to use something tightly coupled and code, rather than as XML and code are loosely coupled (and in some cases even completely separate) Code Description.
If you search for "XML vs. annotations" in Google, you'll see a lot of debate on this issue. The most interesting is the fact that in order to separate XML configuration code and configuration introduced.
Both views may make you very puzzled, the two views seem to constitute a cycle, but each has advantages and disadvantages. Let's understand the difference between the two through an example.
If you want to apply the settings a lot of constants or parameters, in this case, XML is a good choice, because it does not connect with a particular code. If you want a method statement for the service, Annotation would be better to use it, because of the need in this case annotations and methods tightly coupled together, developers must also realize this.
Another very important factor is the Annotation defines a standard way of describing metadata. Prior to this, developers often use custom metadata in their own way. For example, using labeled interfaces, comments, transient keyword, and so on. Each programmer defines the metadata in its own way, unlike Annotation this standard way.
Currently, many XML and Annotation Framework will combine the two to use, advantages and disadvantages balance between the two.

Annotation how it works? How to write Annotation custom?

Before telling this part, I recommend that you first download the sample code AnnotationsSample.zip Annotation of. Download on after you get used to using the IDE, the code will help you better understand Annotation mechanism. Focus on Java technology stack micro-channel public number, reply in the background Keywords: Java, you can get a long stack finishing the latest technology Java Collection.
Annotation is very simple to prepare, Annotation definition can be compared with the definition of the interface. Let's look at two examples: one standard annotation
@Override, the other is a user-defined annotations @Todo.

@Target(ElementType.METHOD)br/>@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

For @Override comments you might have some questions, it did not do anything, then it is how to check the function of the same name in the parent class yet. Of course, do not be surprised, I'm teasing you. define br /> @ Override annotation is not the only so little code. This part is very important, I have to repeat once again: Annotations are only metadata and business logic has nothing to do.
A bit difficult to understand, but that's it. If Annotations do not contain business logic, then someone must enable this logic. User metadata to do this thing. Annotations provide only information (classes / methods / package / domain) that defines the attributes. Annotations users (also some code) to read the information and to implement the necessary logic.
br /> when we use Java annotations Annotations (eg @Override), JVM is a user, it works at the bytecode level. Here, the application developer can not control can not use custom annotations. Therefore, we explain how to write a custom Annotations.
We write about the points one by one in a custom Annotations. In the above example, you see some application notes on the notes.
J2SE5.0 version offers four yuan notes in java.lang.annotation, special notes Other notes:

@Documented - whether notes will be included in the JavaDoc
@Retention - when to use the annotation
@Target -? Notes somewhere for
@Inherited - whether to allow the subclass inherits the comment

@ Documented- a simple Annotations mark notes, annotations indicating whether the information added to the java documentation.
@ Retention- the annotation defined life cycle.
RetentionPolicy.SOURCE - discarded at compile time. These annotations at the end of the compiler will no longer have any meaning, they do not write byte code. @Override, @SuppressWarnings belong to such comments.
RetentionPolicy.CLASS - discarded when the class is loaded. Useful bytecode files. NOTE Using this way by default.
RetentionPolicy.RUNTIME- are never discarded, run also keep the notes, so you can use reflection to read the annotation information. Annotations our custom commonly used in this way.
@Target - indicates that the annotations are used where. If you do not clear that the comment can be placed anywhere. The following are some of the available parameters. It should be noted: annotation properties are compatible, if you want to annotate all seven properties, excluding one property only, then you need to include all of the attributes defined target.

ElementType.TYPE: used to describe the class, interface or enum declaration
ElementType.FIELD: instance variables for describing
ElementType.METHOD
ElementType.PARAMETER
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE another annotation
package ElementType.PACKAGE java file for recording information

@Inherited - define the relationship between the notes and subclass
then, internal notes in the end is how to define it? Annotations supports only basic types, String and enumerated types. Note that all attributes are defined as a method and allows to provide default values.

@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 demonstrates how to use the above comments.

@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 a comment is only one attribute can be directly named as "value", when used without re-labeled property name.

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

But so far everything looks pretty good. We define the method and its application in the business logic of their own comments. Now we need to write a user program call our notes. Here we need to use reflection. If you are familiar reflection code, we know that reflection can provide the class name, methods and instance variables object.
All of these objects have getAnnotation () This method is used to return the annotation information. We need to put this object into a (after using instanceOf () check) our custom annotations, but can also invoke methods to customize the comment inside. Consider the following example code, the use of the above comments:

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());
  }
}

Notes Use Cases

Annotation function is very powerful, Spring and Hebernate these Framework uses annotations and effectiveness in the log. Annotations can be used in place of using the marker interface. The difference is that marker interface used to define the full class, but you can be a single way to define annotation, such as whether the method exposed as a service.
We introduced a lot of new notes in the latest servlet3.0, especially servlet and security-related notes.
HandlesTypes - used to indicate the annotation ServletContainerInitializer passed to a set of application classes.
HttpConstraint - representative of the security constraints of all annotation application requests the HTTP method, and HttpMethodConstraint security constraints defined in the annotation ServletSecurity different.
The method of HTTP protocols describe different types of annotations security constraints specify different types of requests, and ServletSecurity annotations - HttpMethodConstraint.
MultipartConfig - marked on the annotation Servlet above, it indicates that the desired MIME type Servlet processing request is multipart / form-data.
ServletSecurity The notes marked Servlet class inheritance above, forcing the HTTP protocol requests follow the safety constraints.
WebFilter - This annotation is used to declare a Server filter;
WebInitParam - annotation is used to declare the Servlet or filter initialization parameters, or generally with @WebServlet @WebFilter use.
WebListener - The annotations for the Web application in the context of different types of events declared listener.
WebServlet - The annotation is used to declare a Servlet configuration.

ADF (Application Framework) and comments

Now we begin to discuss the last part of the article. Application framework, known as the ADF, the Oracle developer to create Oracle Fusion Applications. We already know the advantages and disadvantages of notes, but also know how to write a custom annotation, but we should be annotated in which part of the ADF application of it? Whether the ADF provides some simple annotations?
Good question, do use a lot of comment in the ADF has some limitations. As previously mentioned application framework Spring and Hibernate using the AOP (aspect-oriented programming). In AOP, the framework provides a mechanism to inject code in the pretreatment and subsequent processing events.
For example: You have a hook for before and after the implementation of the method add code, so you can write your user code in these places. ADF does not use AOP. If we have any notes available, we may need to implement inheritance by way of use cases.

At last

Welcome to share with everyone, like the point of a praise yo remember the article, thanks for the support!

Guess you like

Origin blog.51cto.com/14442094/2429503