Add metadata to Java code

Source: Internet
Author: User

Note: The New Function in j2se 5.0 (TIGER) introduces the much-needed metadata tool into the core Java language. This series of articles is divided into two parts. In this 1st part, the author Brett McLaughlin explains why metadata is so useful and introduces annotations in Java, the built-in comments of tiger are also studied.

A new trend in programming, especially in Java programming, is the useMetadata. In short, metadata isAboutData. Metadata can be used to create documents, track code dependencies, and even perform basic compile-time checks. Many metadata tools, such as XDoclet (see references), add these features to the core Java language and temporarily become part of the Java programming function.

Until j2se 5.0 (also called Tiger, now the second beta version) can be used, the core Java language is the closest to the metadata tool with the javadoc method. You use a special tag set to mark code and executejavadocCommand to convert these tags into formatted HTML pages. This page describes the classes attached to the tags. However, javadoc is a flawed metadata tool because, apart from generating documents, you do not have a fixed, practical, and standardized way to use data for other purposes. The fact that HTML code is often incorporated into javadoc output even further reduces its value for any other purpose.

TigerNoteThe new feature combines a more common metadata tool into the core Java language. Annotation is a modifier that can be added to the code. It can be used for package declaration, type declaration, constructors, methods, fields, parameters, and variables. Tiger includes built-in comments and supports custom comments compiled by you. This article will outline the advantages of metadata and introduce you to the built-in comments of tiger. Part 1 of this series of articles will study custom annotations. I would like to thank o'reilly media, inc ., they generously allow me to use the sample code in the "Comments" section of my tiger book in this article (see references ).

Value of metadata

In general, the benefits of metadata are divided into three types: Documentation, compiler checks, and code analysis. Code-level documents are most often referenced. Metadata provides a useful method to indicate whether a method depends on other methods, whether they are complete, whether a specific class must reference other classes, and so on. This is indeed very useful, but for Adding metadata to the Java language, the documentation may beLeastRelated reasons. Javadoc provides easy-to-understand and robust methods to document code. In addition, who else needs to write a document preparation tool when there is already a document preparation tool and most of the time it works well?

Do not miss another part of this series

Be sure to read "Part 1" of this series, which studies custom annotations.

Compiler check

The more important advantage of metadata is that the compiler can use it to perform basic compile-time checks. For example, you will see in the override comment after this article that tiger introduces such a comment to allow you to specify a method to override another method in the superclass. The Java compiler ensures that the behavior specified in the metadata actually occurs at the code level. If you have never found such a type of Bug, it seems silly to do so, but most older Java programmers have spent at least one night figuring out why their code is useless. When we finally realize that the parameters of the method are wrong, and the method is actuallyNoYou may feel more uncomfortable when overwriting methods in the superclass. Using metadata tools helps you easily identify errors of this type, saving you time to watch the long-term halo league.

Jsr175

Jsr175,Java programming language metadata ToolTo merge the metadata into the core Java language (see references ). According to the JSR, the comment "does not directly affect the semantics of the program. However, development and deployment tools can read these annotations and process them in some form, other Java programming language source files, XML documents, or other components to be used with annotated programs may be generated."

Code Analysis

It can prove that the best feature of any good annotation or metadata tool is to use additional data to analyze code. In a simple case, you may build a code directory, provide the required input type, and specify the returned class type. However, you may think that Java reflection has the same advantages. After all, you can save code for all this information. This seems to be correct on the surface, but it is usually not used in reality. In many cases, methods accepted as input or returned as output are not actually the type that this method wants. For example, the parameter type may beObjectBut the method may only useInteger. This is easy to happen in some situations. For example, when methods are overwritten and superclasses use conventional parameter declaration methods, there are also systems that are undergoing many serialization. In both cases, metadata can indicate the code analysis tool, although the parameter type isObject,IntegerIs really needed. This type of analysis is very useful, but it cannot be exaggerated.

In more complex cases, code analysis tools can execute all types of additional tasks. The example du jour is an Enterprise JavaBean (EJB) component. Even the dependencies and complexity in simple EJB systems are surprising. You have the home interface and remote interface, as well as the local interface and local home interface, and an implementation class. It is very difficult to keep all these classes synchronized. However, metadata can provide solutions to this problem. Good tools (or mention XDoclet) can manage all these dependencies and ensure that classes without "code-level" connections but with "logic-level" bundle are synchronized. Metadata can indeed play its role here.



Back to Top

Basic annotation knowledge

Now that you know the benefits of metadata, I will introduce annotations in tiger. Annotations are marked as "(@), Followed by the annotation name. Thenname=valueProvide data to comments. Every time this type of notation is used, a comment is generated. A piece of code may have 10, 50, or more comments. However, you will find that multiple annotations may use the sameAnnotation type. The type is the structure actually used. in a specific context, the Comment itself is the specific use of this type (see the sidebar comment or comment type ?).

Annotation or annotation type?

Are you confused about what is annotation and what is annotation type? The simplest way to understand this is to compare the familiar Java language concepts. You can define a class (for examplePerson), Only one version of the class is available in JVM (assuming there is no troublesome class path setting ). However, at any given time, 10 or 20 of the class may be used.Instance. There is still only onePersonClass, but it is used multiple times in different ways. The same is true for annotation types and annotations. The annotation type is similar to a class, and the annotation is similar to an instance of this class.

There are three basic types of Annotations:

  • Mark commentsNo variables. The comment display is simple, identified by the name, and no other data is provided. For example,@MarkerAnnotationYes. It does not contain data and only has a comment name.

  • Single value commentSimilar to marking comments, but providing a piece of data. Because only a small amount of data is provided, you can use the shortcut syntax (assuming that the annotation type accepts this syntax ):@SingleValueAnnotation("my data"). Besides@This should be similar to a normal Java method call.
  • Complete commentsHas multiple data members. Therefore, you must use a more complete syntax (annotations are no longer like common Java methods ):@FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3").

In addition to providing values to annotations using the default syntax, you can also use name-value pairs when you need to transmit multiple values. You can also provide a value array for the annotation variable through curly brackets. Listing 1 shows an example of a value array in the comment.

Listing 1. Using values arranged by array in comments

@TODOItems({    // Curly braces indicate an array of values is being supplied
@TODO(
severity=TODO.CRITICAL,
item="Add functionality to calculate the mean of the student's grades",
assignedTo="Brett McLaughlin"
),
@TODO(
severity=TODO.IMPOTANT,
item="Print usage message to screen if no command-line flags specified",
assignedTo="Brett McLaughlin"
),
@TODO(
severity=TODO.LOW,
item="Roll a new website page with this class's new features",
assignedTo="Jason Hunter"
)
})

The examples in Listing 1 are not as complex as they are at first glance.TODOItemsThe annotation type has a variable with a value. The value provided here is complex,TODOItemsThe usage is actually consistent with the comment type of a single value, but the single value here is an array. The array contains threeTODOAnnotations, where each annotation is multi-value. Separate values in each comment with commas (,) and values in a single array. Very easy, right?

But I may be ahead of schedule.TODOItemsAndTODOYesCustom commentsIs the topic in part 1 of this series of articles. But I want you to see that even complex comments (listing 1 is almost the most complex comments) are not very scary. When we mention the standard annotation type of Java, We will rarely see such a complex situation. As we will see in the following three sections, the use of Tiger's basic annotation types is extremely simple.



Back to Top

Override comment

The first built-in annotation type of tiger isOverride.OverrideIt should be used only for methods (not for classes, package declarations, or other constructor ). It indicates that the annotated method will overwrite the methods in the superclass. Listing 2 shows a simple example.Listing 2. Override comment in the operation

package com.oreilly.tiger.ch06;
public class OverrideTester {
public OverrideTester() { }
@Override
public String toString() {
return super.toString() + " [Override Tester Implementation]";
}
@Override
public int hashCode() {
return toString().hashCode();
}
}

Listing 2 should be easy to understand.@OverrideThe two methods are annotated-toString()AndhashCode()To indicate that they are overwritten.OverrideTesterClass superclass (java.lang.Object. This may seem useless at first, but it is actually a very good function. If these methods are not overwrittenNoCompile this class. This note also ensures that when youtoString()There should be at least some indication in case of chaos, that is, make sure thathashCode()Still match.

When encoding is very late and something is wrong, this annotation type can really play a major role, as shown in listing 3.

Listing 3. Enable override annotation to capture the typing draft

package com.oreilly.tiger.ch06;
public class OverrideTester {
public OverrideTester() { }
@Override
public String toString() {
return super.toString() + " [Override Tester Implementation]";
}
@Override
public int hasCode() {
return toString().hashCode();
}
}

In listing 3,hashCode()Incorrect input:hasCode(). DescriptionhasCode()The method should be overwritten. However, during compilation,javacSuper class (java.lang.Object) No NamehasCode()Can be overwritten. Therefore, the compiler reports an error, as shown in 1.

Figure 1. compiler warning from override comments

Missing features

In a single value annotation type, ifDeprecatedIt is better to allow messages that contain error types. Then, the compiler can print messages when the user uses a declared obsolete method. This message indicates how important the result of using the method is, indicating when the method will be stopped, or even the alternative method is recommended. This feature may be available in the next j2se version ("Mustang", which is named like this.

This easy-to-use small feature will help you quickly capture typed documents.



Back to Top

Deprecated Annotation

The next standard comment type isDeprecated. AndOverrideSame,DeprecatedYes. As you may expect, you can useDeprecatedTo comment out methods that should not be used. AndOverrideThe difference is that,DeprecatedIt should be placed in the same line as the method being declared as obsolete (why? I don't know), as shown in Listing 4.Listing 4. deprecated Annotation

package com.oreilly.tiger.ch06;
public class DeprecatedClass {
@Deprecated public void doSomething() {
// some code
}
public void doSomethingElse() {
// This method presumably does what doSomething() does, but better
}
}

This class will not be different when compiled separately. However, if the declared method is overwritten or called, the compiler processes the annotation and finds that this method should not be used and sends an error message, as shown in 2.

Figure 2. compiler warning from deprecated comments

Note that you need to enable the compiler warning, as if you must specify to the Java compiler that you want a common declaration as an out-of-date warning. You can use either of the following two tags andjavacCommand:-deprecatedOr new-Xlint:deprecatedMark.



Back to Top

Suppresswarnings comments

The last annotation type obtained from Tiger "free" isSuppressWarnings. It is not difficult to find the role of this type,Why?This annotation type is usually not very important. It is actually a sub-function of all the new functions of tiger. For example, taking generics as an example, generics make all types of new security operations possible, especially when Java collections are involved. However, because of genericsNoWhen the type is safe, the compiler throws a warning. This is helpful for tiger code, but it makes it very troublesome to write code for Java 1.4.x or earlier. You will receive continuous warnings about irrelevant things. How can the compiler not bother you?

SupressWarningsThis problem can be solved.SupressWarningsAndOverrideAndDeprecatedDifferent,YesWith a variable-so you use a single annotation type with the variable. A value array can be used to provide variables. Each value indicates a specific warning type to block. See the example in listing 5. This is the code that usually produces errors in tiger.

Listing 5. Not type-safe tiger code

public void nonGenericsMethod() {
List wordList = new ArrayList(); // no typing information on the List
wordList.add("foo"); // causes error on list addition
}

Figure 3 shows the compilation result of the Code in listing 5.

Figure 3. compiler warning from non-standard code

Listing 6 UseSuppressWarningsAnnotations eliminate this problem.

Listing 6. Blocking warnings

@SuppressWarings(value={"unchecked"})
public void nonGenericsMethod() {
List wordList = new ArrayList(); // no typing information on the List
wordList.add("foo"); // causes error on list addition
}

Very simple, right? You only need to locate the Warning type (shown in Figure 3 as "unchecked") and send itSuppressWarnings.

SuppressWarningsThe value of the variable in uses an array, so that you can block multiple warnings in the same comment. For example,@SuppressWarnings(value={"unchecked", "fallthrough"})Use an array of two values. This function provides a flexible way to handle errors without much work.

 

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.