Author: Jason hunter
Learn how to use the Metadata Annotation provided in j2se 5.0
The latest j2se 5.0 version (also known as "tiger") introduces many changes to the Java language, designed to make Java programming more expressive, developer friendly, and safer. One of my questions in September 2003 was"Java is about to change dramatically"ArticleDescribes many new Java features. I did not introduce a major change-it was not yet a complete overview-it was a Java metadata tool. From the beginning of this article, in a new four-part article series, I will continue to show you how to make full use of Java metadata from where I left a year ago.
In the first article, I will describe the usage of metadata and demonstrate how to use the metadata annotations provided in the core j2se database.
In the second article, I will show you how to write your own comments (First, write simple comments similar to @ copyright, then look at the more advanced annotations that are similar to those built in the core language ).
In the third article, I will demonstrate how the tool uses annotations (creating new source files or supporting files) during build andProgramHow to Use annotations (to changeCode).
In the fourth article, I will show you how to make it easier to edit and deploy Web Services in the future by using the help of standard metadata annotations developed under the JSR-181 (Oracle is a member of the Expert Group of the JSR-181, it is also an active supporter of adding support for metadata during design in development tools .)
Metadata
I admit when I first saw the JSR-175 Proposal"For JavaProgramming LanguageMetadata Tool"(Released in September 2004; oracle was also a member of the Expert Group), I predicted it would create another property file that must be placed under the jar META-INF directory, or another XML deployment descriptor that must be bundled with jar. Fortunately, this is not the metadata. In fact, it is the opposite. Java's new metadata tool provides a standard way to annotate Java code from inside Java code. It enables you to place descriptive metadata next to the element you want to describe.
When discussing metadata, you will often see several similar terms, so the following provides a small glossary to help you understand their differences:
Terms |
Definition |
Metadata |
Data about the data. The goal of the JSR-175 is to provide metadata tools in the Java language. |
Annotation |
A special Java structure used to modify classes, methods, fields, parameters, variables, constructors, or packages. It is a tool that JSR-175 selects to provide metadata. |
Annotation type |
Various naming annotations with special implementations |
Attribute |
A special metadata item specified by the annotation. Sometimes it can be used with annotations. |
For example, Fuji Apple has a property: It is red. Assume there is a fujiapple class, you can use@ ColorAn Annotation of the annotation type to specify its color. By doing so, you provide metadata about Apple.
Java has always had metadata requirements since Version 1.0. Java has never provided a standard mechanism for recording metadata, so our programmers have found various techniques and tips to use any tool to add metadata. You can see that metadata is used in j2se 1.4 and earlier versions:
- Transient keyword
- Serializable flag Interface
- Singlethreadmodel servlet Interface
- Elements inside the Web. xml deployment descriptor
- META-INF/manifest. MF File
- Beaninfo Interface
- @ Deprecated javadoc Annotation
- All XDoclet javadoc labels.
When using these techniques, you may not have imagined that you are adding metadata, but you are actually Adding metadata. The problem with the above methods is that they are all different methods for solving the same problem, but the versatility is not good. Each method has at least one drawback that is addressed in the new metadata tool.
The limitations of some methods in this list are obvious. Keywords cannot be scaled; you cannot use custom keywords. The markup interface does not provide any information except their existence (that is, they do not contain parameters), and they can only process classes, rather than fields, methods, or packages.
Other methods in the list may look reasonable. It seems a good idea to use XML to support files, but in fact it is still a good idea in many cases. However, for many purposes of using XML files, such as indicating which method of the class should be regarded as a web service, it is more efficient to put rules directly next to methods in Java code. With metadata, you can make the XML descriptor file only contain deployment-related decisions.
The most efficient metadata usage in this list is @ deprecated javadoc annotation and the XDoclet tag created in its image. This may be why the JSR-175 syntax looks very similar to the @ deprecated mark (as we will see in the next section ).
Annotation
Annotations can be easily appended to the code structure. You can write an "at" symbol (@), followed by the annotation type name, and place the annotation directly before the project to be annotated. The following is a simple example:
Import javax. JWS. WebService; import javax. JWS. webmethod; @ webservicepublic class helloworldservice {@ webmethodpublic string helloworld () {return "Hello world! ";}}
When deployed in the correct environment, add@ WebServiceAnd@ WebmethodThe annotation indicates that the Web service environment changes the class to a web service.
You can annotate methods, classes, fields, parameters, variables, constructors, and even the entire package (using a special external package-info.java file ). Annotations can contain any number of naming parameters in brackets. The following is a more advanced sample class that uses annotations to create Web Services. It contains a theoretical JNDI Environment Variable Search:
@ WebService (name = "pingservice", targetnamespace = "http://acme.com/ping") @ soapbinding (style = soapbinding. style. RPC, use = soapbinding. use. literal) public class ping {public @ env double level = 500.0; // JNDI lookuppublic @ webmethod (operationname = "foo") {void Foo (){}}}
This example shows the annotations appended to classes, variables, and methods (there are actually two methods in the class.@ EnvThe annotation does not have any parameters, so it does not need parentheses. Other annotations have one or more named parameters.
When creating a new annotation type, you will limit which parameter names and their types are allowed. The types accepted by the annotation are strictly limited; they can only be basic types, String, class, enumeration type, annotation type, and arrays of the previous types. The passed parameters must always be non-empty compilation times.
To understand the effect of the annotation shown in this example, you must wait until the fourth article in this series. Let's take a look at the simple annotation types provided by j2se 5.0:@ Override, @ deprecatedAnd@ Suppresswarnings.
Built-in annotations
When looking at these three standard user-level annotations, we must consider: among all possible annotation types that can be provided, why does tiger provide exactly three types? The reason is that a large number of standard comments are not the target.
The purpose of the JSR-175 is strictly stipulated that it is to define a metadata tool. The task of writing a custom annotation type is left to the programmer, while the task of writing a set of standard annotation types is left to other jsrs. For example, there is a new JSR-250 named "Java platform generic annotation" whose purpose is "to develop the annotation that applies to various technologies for general semantic concepts in j2se and J2EE platforms ". The JSR-250 plans to provide its standard annotation set in the javax. Annotations package at some point in the spring of 2005. There is also the JSR-181 mentioned earlier, which will make it easier to write Web Services in J2EE containers (which we will introduce in the fourth article in this series ). In fact, most new enterprise JSR (from servlets 2.5 to EJB 3.0 to JDBC 4.0) are considering the advantages of annotation.
@ Override
First j2se standard Annotation@ OverrideThis allows you to add new optional compiler checks in your code. It exists in the method, indicating that the method is used to overwrite the method in the parent class. If the compiler detects that this method does not actually overwrite anything, a compilation error occurs. Frequently used,@ OverrideThis helps you avoid minor bugs when the method tag is not fully matched-when the polymorphism changes to (you can call it) "single State" ("unimorphism.
For example, the following code may look reasonable:
Public class overrideexample {@ overridepublic Boolean equals (overrideexample OBJ) {return false ;}}
However, when you compile overrideexample. Java, you will get an error indicating a subtle problem.
% Javac overrideexample. javajavac overrideexample. javaoverrideexample. Java: 3: method does not override a method from its superclass @ override ^ 1 error
By prompting the compiler that you want to overwrite, the compiler can capture minor bugs in the equals () method with object-type parameters.
@ OverrideDoes annotation actually work? Only when you are willing to use@ OverrideIt is useful for programmers who are very rigorous in marking every coverage method. How many of us can claim this degree of rigor? I don't think I can. Maybe ide will find a way to encourage or force use@ Override.
@ Deprecated
The second standard annotation is@ DeprecatedIt has almost the same behavior as the @ deprecated javadoc mark. You can use it in the following ways:
Public class deprecatedexample {@ deprecatedpublic static void badmethod () {}} public class deprecateduser {public static void main (string [] ARGs) {deprecatedexample. badmethod ();}}
The@ DeprecatedThe annotation looks very similar.@ DeprecatedMark, except that it appears before the annotation method or class declaration, and there is an uppercase letter "D ". If you try to compile the above Code, javac generates a warning:
% Javac deprecated *. javanote: deprecateduser. Java uses or overrides a deprecated API. Note: recompile with-xlint: deprecation for details.1 Error
If you follow the warning suggestions and use-Xlint: deprecationThen you will get detailed information about the warning:
% Javac-xlint: deprecationdeprecateduser. Java: 3: Warning: [deprecation] badmethod () in deprecatedexamplehas been deprecateddeprecatedexample. badmethod ();
@ DeprecatedAnnotation Ratio@ OverrideMore useful? I don't think so. This annotation does not support any parameters. Therefore, unlike the javadoc tag, you cannot provide a string to indicate that you do not agree to use this method and recommend an alternative method.@ DeprecatedValue ratio provided by Annotation@ DeprecatedFew tags. The only advantage of this annotation is that you can program the program to detect items that do not approve of use at runtime. Therefore, the traditional viewpoint is that we should use both@ DeprecatedMark and@ DeprecatedMark, one for the document, and the other for runtime reflection.
I think unfortunately JSR-175 has no choice@ DeprecatedDo more work. At least this annotation should be copied@ DeprecatedThe flag function contains a string description so that the compiler can output it together with the deprecation warning. Using additional parameters,@ DeprecatedYou can also receive "iserror" Boolean parameters, to indicate whether this method is not encouraged at all or whether it will be considered as a compilation error (Use A Clear Custom description that explains the cause of the Error for improvement ). View Example 1 of C # And find the property[Obsolete]This attribute is exactly implemented and proved to be very useful.
@ Suppresswarnings
The last annotation provided by j2se is@ Suppresswarnings. The purpose of this annotation is to give the compiler an instruction to tell it to remain silent for some internal warnings of the annotated code element.
A little background: j2se 5.0 has added several new features for the Java language, added many new warnings together with them, and promised to add more warnings in the future. You can add-XlintParameters to control whether to report these warnings (as shown above@ Deprecated).
By default, the sun compiler outputs warnings in two simple rows. Add-Xlint:KeywordMark (for example-Xlint: Finally), You can get a complete description of the keyword type error. Add a break number before the keyword and write it-Xlint:-KeywordYou can cancel the warning. (-XlintThe complete list of supported keywords can be found inJavac document page.) The following is a list:
Keywords |
Purpose |
Deprecation |
Warning when an unsupported class or method is used |
Unchecked |
Warning when an unchecked conversion is executed. For example, when using a set, you do not use generic to specify the type of the set to be saved. |
Fallthrough |
Warning when the switch block directly leads to the following situation without a break. |
Path |
Warning when a path does not exist in the class path or source file path. |
Serial |
Warning when serialversionuid definition is missing in serializable classes. |
Finally |
Warning when any finally clause cannot be completed normally. |
All |
Warning about all the above situations. |
@ SuppresswarningsAnnotations allow you to selectively cancel warnings in a specific code segment (that is, a class or method. The idea is that when you see a warning, you will investigate it. If you are sure it is not a problem, you can add@ SuppresswarningsAnnotate so that you no longer see the warning. Although it seems to block potential errors, it will actually improve code security because it will prevent you from being indifferent to warnings-every warning you see will be worth noting.
Use@ SuppresswarningsTo cancel the deprecation warning:
Public class deprecatedexample2 {@ deprecatedpublic static void Foo () {}} public class deprecateduser2 {@ suppresswarnings (value = {"deprecation"}) public static void main (string [] ARGs) {deprecatedexample2.foo ();}}
@ SuppresswarningsAnnotation receives a "value" variable, which is a string array that indicates a warning that will be canceled. The set of valid strings varies with the compiler, but on JDK, it can be passed-XlintIs the same keyword set (very convenient ). It also requires the compiler to ignore any keywords that they cannot recognize, which is very convenient when you use different compilers.
Subsequent steps Read the draft public review of JSR 175 specifications Read Debu panda's "using EJB 3.0 to simplify EJB development" (from theserverside.com) Read "do you want to use comments?" by Mike Keith ?" DownloadG Tutorial: EJB 2.1 tips |
Because@ SuppresswarningsThe annotation only receives one parameter and uses a special name "value" for this parameter. Therefore, you can omit value = as a convenient Abbreviation:
Public class deprecateduser2 {@ suppresswarnings ({"deprecation"}) public static void main (string [] ARGs) {deprecatedexample2.foo ();}}
You can pass any number of string values in a single array parameter to the annotation and place the annotation at any level. For example, the following sample code indicates that the deprecation warning of the entire class will be canceledMain ()The unchecked and fallthrough warnings are canceled in the method code:
Import Java. util. *; @ suppresswarnings ({"deprecation"}) public class nongenerics {@ suppresswarnings ({"unchecked", "fallthrough"}) public static void main (string [] ARGs) {runtime. runfinalizersonexit (); List list = new arraylist (); list. add ("foo");} public static void Foo () {list = new arraylist (); list. add ("foo ");}}
@ SuppresswarningsIs it more useful than the first two annotations? Absolutely. However, JDK 1.5.0 does not fully support this annotation. If you use 1.5.0 to try it, it will be similar to no operation command. Calling-xlint:-deprecation has no effect. Sun does not declare when support will be added, but it implies that this will be implemented in an upcoming dot version.
Further steps
If you try to view these attributes on the javadocs page, it may be difficult to find them. They are located in the core Java. lang package, but a little concealed. They appear at the bottom of the javadoc class and are listed behind the exceptions and errors.
Note the strange annotations appended to the suppresswarnings Annotation@ TargetAnd@ Retention? These are called metadata annotations, which describe where the annotation applies. I will introduce them in the second article in this series and how to apply metadata annotations to your own annotations.
Jason hunter Wrote 《Java Servlet ProgrammingAnd co-authored with others 《Java Enterprise best application(Both are published by o'reilly ). He is a member of Apache and serves as the representative of Apache to the Executive Council of Java group development processes.Source codeMilestone agreement. He isServlets.comAndXquery.comThe initiator, the earliest contributor to Apache Tomcat, the founder of COM. oreilly. servlet library, and a member of the expert group responsible for servlet, JSP, JAXP, and xqj API development. He isJDOM LibraryOne of its founders, the JDOM library implements optimized Java and XML integration. In 2003, he got Oracle magazine OfAnnual editingPrize.