Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Java work?

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how Java works. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

1. What is the note?

It can be explained in one word: annotations are metadata. Metadata is data about data. So annotations are metadata for the code. For example, look at the following code.

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

I used the @ Override annotation when I overridden the toString () method in the above code. Even if I don't use @ Override, the code still works without any problems. So, what are the advantages of this annotation? What does it stand for? @ Override tells the compiler that this method is an overridden method (about the method's metadata) and throws a compiler error (no method overridden in the superclass) if such a method does not exist in the parent class. Now, if I make a typesetting error and use the method name toStrring () {double r} if I don't use @ Override, my code will compile and execute successfully, but the result will be different than expected. Now that we understand what annotations are, it is useful to read the formal definition.

Annotations are special Java constructs that modify classes, methods, fields, parameters, variables, constructors, or packages. This is the tool chosen by JSR-175 to provide metadata.

two。 Why are annotations introduced?

Before (and even after) annotations, XML was widely used for metadata, but some specific application developers and architects thought XML maintenance became cumbersome. They want to be able to be tightly coupled to the code in some way instead of XML, because XML and the code are very loosely coupled (and, in some cases, almost independent). If you Google "XML vs annotations", you will find a lot of interesting arguments. Interestingly, the XML configuration was introduced to separate the configuration from the code. The last two statements may raise some questions in your mind that both statements are creating a cycle, but each has its own advantages and disadvantages. Let's try to understand it with an example.

Suppose you want to set some application-wide constants / parameters. In this scenario, XML would be a better choice because it has nothing to do with any particular code snippet. If you want to expose certain methods as services, annotations are a better choice because it needs to be tightly coupled to the method, and the developers of the method must know this.

Another important factor is that annotations define a standard way to define metadata in your code. Before annotating, people also use their own methods to define metadata. Some examples are the use of tag interfaces, annotations, temporary keywords, and so on. Every developer needs to determine metadata in his or her own way, but annotations are standardized.

Today, most frameworks combine XML and annotations to take full advantage of both.

3. How annotations work and how to write custom annotations

Before starting the explanation, I recommend that you download the sample code for this AnnotationsSample.zip and keep it open in your common IDE, as it will help you better understand the following explanation.

Writing annotations is very simple. You can compare annotation definitions with interface definitions. Let's look at two examples-one is the standard @ Override, and the second annotation is a custom annotation. @ Todo:

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

There seems to be something suspicious about @ Override it doesn't do anything-it just checks to see if a method is defined in the parent class. Don't be surprised, I'm not kidding. There is only so much code to rewrite the definition of annotations. This is the most important part to understand, and I repeat: * * annotations are only metadata and do not contain any business logic. * * it's hard to understand but it's true. If the annotation does not contain logic, then someone must be doing something, and someone is the consumer of the annotation metadata. Annotations provide only information about defined properties (classes / methods / packages / fields). The consumer is a piece of code that reads this information and then executes the necessary logic.

When we talk about standard annotations, such as @ Override, JVM is the user, which works at the bytecode level. This is something that application developers cannot control and cannot be used for custom annotations. Therefore, we need to write some consumption examples for our own comments.

Let's understand the key terms used to write annotations one by one. In the above example, you will see how annotations are applied.

J2SE 5.0provides four annotations in the java.lang.annotation package that are used only when writing annotations:

> @ Documented-whether to put annotations in Javadocs > > @ Retention-when annotations are retained > > @ Target?-where annotations can be used > @ Inherited-whether subclasses can inherit annotations.

Documented-A simple tag annotation that identifies whether or not to add annotations to the Javadoc.

Retention-defines how long comments should be retained.

RetentionPolicy.SOURCE is discarded during compilation. These annotations have no meaning after compilation, so they are not written to bytecode. Example: @ Override, @ SuppressWarnings

RetentionPolicy.CLASS-discarded during class loading. Applied during bytecode-level compilation. Somewhat surprisingly, this is the default.

RetentionPolicy.RUNTIME-will not be discarded. This annotation can be reflected at run time. This is what we usually use for custom annotations.

@ Target-where annotations can be used. If you do not specify this attribute, annotations can be applied anywhere. The following are valid values for this comment. One important point here is that it has only the included form, which means that if you want to annotate seven attributes and want to exclude only one attribute, you need to include all seven attributes when defining the target.

> ElementType.TYPE (classes, interfaces, enumerations) > > ElementType.FIELD (instance variables) > > ElementType.METHOD > > ElementType.PARAMETER > > ElementType.CONSTRUCTOR > > ElementType.LOCAL_VARIABLE > > ElementType.ANNOTATION_TYPE (for other annotations) > > ElementType.PACKAGE (remember package-info.java)

Inherited-controls whether annotations should affect subclasses.

Now, what is included in the annotation definition? Annotations only support basic types, strings, and enumerations. All properties of the annotation are defined as methods, and default values can also 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 is an example of how to use the above annotations:

@ 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 should be named "value" and can be used without the attribute name.

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

So far so good. We have defined custom annotations and applied them to some business logic methods. Now, it's time to write an example of consumption. To accomplish this goal, we need to use reflection. If you are familiar with reflection code, you know that reflection provides classes, methods, and field objects. All of these objects have a getAnnotation () method, which returns the annotation object. We need to convert this object to a custom annotation (after checking with instanceOf ()), and then we can call the methods defined in the custom annotation. Let's take a look at the sample code, which uses the above annotation:

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 ());}} 4. Annotation use case

Annotations are very powerful, and frameworks such as Spring and Hibernate make extensive use of annotations for logging and verification. Annotations can be used where tagging interfaces are used. The tag interface is used for the entire class, but you can define annotations that can be used for a single method, such as whether a method is exposed as a service method.

In the servlet 3.0 specification, many annotations have been introduced, especially those related to servlet security. Let's first take a look at a few:

HandlesTypes-this annotation is used to declare an array of application classes passed to ServletContainerInitializer.

HttpConstraint-this comment represents the security constraint that applies to all requests with the HTTP protocol method type, when there is no corresponding HttpMethodConstraint comment on ServletSecurity.

HttpMethodConstraint-specific security constraints can be applied to different types of requests, annotated on ServletSecurity.

MultipartConfig-this comment is used to indicate that the servlet that declares it will use the multiPart/form-Data MIME type to make the request.

ServletSecurity-declare this comment on the servlet implementation class to enforce security constraints on HTTP protocol requests.

WebFilter-comments used to declare servlet filters.

WebInitParam-A comment that declares initialization parameters on a servlet or filter and comments on WebFilter or WebServlet.

WebListener-comments for listeners that declare various types of events in the context of a given Web application.

WebServlet-this annotation is used to declare the configuration of servlet.

5. Application Development Framework (ADF,Application Development Framework) and annotations

Now, the last part we're talking about: the Application Development Framework (ADF). ADF is developed by Oracle and is used to build Oracle converged applications. We have seen the pros and cons and know how to write custom annotations, but where can we use custom annotations in ADF? Does ADF provide local comments?

These are certainly interesting questions: but are there any restrictions that prevent large-scale use of annotations in ADF? AOP (aspect-oriented programming) is used by the aforementioned frameworks such as Spring and Hibernate. In AOP, the framework provides a mechanism to inject code for preprocessing and post-processing of any event. For example, you have a hook to place code before and after method execution, so you can write custom code in these places. ADF does not use AOP. If we have any valid annotation use cases, we may need to use inheritance. This is the end of the article on "how Java works". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report