1.1. Background
J2SE (TM) 5.0 has been officially released for more than 3 months, just before, probably two weeks ago, Sun also released the updated JDK 5.0 Update 1, replenished some of the first release Bug appearing.
Since the Java community waits for a considerable period of time from 1.4 to 5.0 version, everyone is very concerned about what is worth paying attention to in 5.0, so Blog's related information is full of flight, I also hit the blog in my own blog. Add a series of articles. Helpless these blog articles, including my own, usually a general, so the editorials of the 9CBS second phase Java e-magazine plan to make a special discussion on this topic and the relevant people.
As part of this electronic publication, the editors also invited me to explore: What are the practical uses of newly introduced language characteristics in J2SE (TM) 5.0, and why these new features are introduced. I am very honored to this. I am very happy to share some Java experience, I may share with you, I hope this small text can help you know J2SE (TM) 5.0.
1.2. Preparation
First, in order to understand the new language characteristics of J2SE (TM) 5.0, you need to download the new version of JDK, you can find the download link here:
http://java.sun.com/j2se/1.5.0/download.jsp. Of course, if you have already manually configured the experience of the Java environment, I also recommend you use a IDE that supports J2SE (TM) 5.0, recommended Eclipse SDK 3.1 M4, or NetBeans IDE 4.0. Both are open source free, and it is easy to find (Eclipse doesn't have to say, NetBeans IDE 4.0 has a bundle with JDK 5.0 Update 1).
Say the problem out, Java's version number has since started from 1.2, it seems to be a little feet. Starting from version 1.2, Java (J2SE) is called Java 2, not Java 1.2, now looks more bizarre: Java (TM) 2 Platform Standard Edition 5.0 or J2SE (TM) 5.0, and the internal version number is also 1.5. 0. So is it 1, 2, or 5? Take a look at how Sun's official website says:
It has been 9 years since Java has been found, and there is also 5 years from the second generation Java platform J2SE. In this background, the next version of the version number is changed from 1.5 to 5.0 can better reflect the maturity, stability, scalability, and safety of the new J2SE.
Ok, now we will face some names, and they are basically the same thing:
l Tiger
l Java (TM) 2 Platform Standard Edition 5.0
L J2se (TM) 5.0
l Java Version 1.5.0
l ...
In this article, I will use J2SE (TM) 5.0 name for convenience.
If you are interested in the code of Java, like "Tiger" here, you can refer to the following URL:
Http://java.sun.com/j2se/codenames.html. Lenten: Java's next version (6.0) code is "Mustang" wild horse, then the next version (7.0) code is "Dolphin" dolphin.
Overview
J2SE (TM) 5.0 introduces a lot of radical language elements, these changes or less reduced some of our developers' coded burdens, most of which will inevitably be applied to the upcoming J2EE (TM) 5.0. The main new features include:
L gear
l Enhanced for loop
l automatic packing and automatic unpacking
l Type safety enumeration
l variable length parameters
l Static introduction
L metadata (annotation)
L C style formatting output
Among this, generics, enumerations, and annotations may take up a large space, while the rest is because of the use of straightforward, or relatively simple, I will introduce, and the rest is left to readers to think, and explore.
1.4. Generic
This topic is quite large, and you can write a book on this topic. Regarding whether Java requires generics and how to achieve generic discussions have also spread in Java community. Finally, we have seen it in J2se (TM) 5.0. Perhaps the current Java's support is still enough, but the addition of this feature is also enough to make us happy.
In the next introduction, we will learn that although Java's generics look very similar to C generics, there is actually a considerable difference, and some details are quite complicated (at least many places will follow us. Intuitive lanes). It can be said that the introduction of generics increases the complexity of Java language to a large extent, and for beginners, especially challenges. Below we will dig at a little bit.
First let's take a simple example of using generic classes:
ArrayList
Alist.add (New Integer (1));
// ...
Integer myinteger = alist.get (0);
We can see that in this simple example, we specify it when defining alist, it is an arraylist directly at the integer type. When we call Alist.get (0), we no longer need to explicit first. Convert the result into an Integer and then assign the value to Myinteger. This step is necessary in the earlier Java version. Maybe you are thinking, save some types of conversions when using Collection? Is the Java generic? Far. In this example, there is at least a bigger advantage in this example, that is, using generic container classes become more robust: earlier, the collection interface's get () and item () method of the Iterator interface are only Can return the result of the Object type, we can force this result into any Object's subclass without any compile period, but it is obviously likely to bring a serious runtime error because it is determined in the code. What type of object takes out in a collection is completely caller, and the caller may not clearly put it into the COLLECTION object. What is the type of object that knows that the object is "should"? It is also not possible to ensure that the object of the Collection must be the example of that class. Now there is a generic, as long as we define which type of object that the Collection is accepted, the compiler can help us avoid similar problems to the product. In fact, we have seen too many ClassCastException, isn't it?
The use of generics is quite easy to understand from this example. When we define the ArrayList, we specify the type of object accepted this ArrayList through the value in the <> brackets behind the class name. At compilation, this ArrayList will be processed into objects that only accept this class or its subclass, so that any statements that have tried to add other types of objects will be rejected by the compiler. So how is a generic definition? Take a look at the sample code below: (here, using E instead of the class name that will be used in the actual situation, of course, you can also use other names, habits to use uppercase of E, indicating the elements of Collection.)
Public Class TestGenerics
Collection
Public void dosth (e elem) {
Col.Add (ELEM);
// ...
}
}
In generic use, there is a very misunderstanding, that is, since INTEGER is derived from Object, ArrayList
Next we step further: Since ArrayList Extends SomeClass> is a wild public parent class, can we add a SomeextendedClass1 object to the arraylist instance declared for ArrayList
C.ADD (ELEM);
}
Where t represents the final specific class expected by our method, the relevant statement must be placed before the method signature is tight against the type of return. In this example, it can be some subclasses of SomeClass or SomeClass, indicating that
The greatest feature of Java generics is that it is implemented in the language level, which is distinguished in CLR level in C # 2.0. This approach allows JRE to do not have to make big adjustments, and the disadvantage is that it is unable to support some of the type screening of the runtime. Once compiled, it is written, and the dynamic capacity that can be provided is quite weak.
Personally, the generic is the most important language element introduced in J2SE (TM) 5.0, which has the greatest impact on Java language. For example, we can see that almost all Collections APIs are updated to support generic versions. The benefits of doing this are obvious, that is, reduce code repetition (no need to provide a certain class or interface of multiple versions to support different types of objects) and enhance the robustness of the code (the type security check of the compile period). But how can I truly use this characteristic, especially how to implement my generic interface or class for others, it is not so obvious. Let us slowly accumulate in use.
1.5. Enhanced for cycle
Have you tired of every time you write for loops, especially when you need to traverse an array or collect, such as: (assuming that the object stored in the Collection is String type)
Public Void Showall (Collection C) {for (Iterator iter = C.ITerator (); ore.hasnext ();) {
System.out.println (String) iTer.next ());
}
}
Public void showall (String [] sa) {
For (int i = 0; i System.out.println (SA [i]); } } This code is not only bloated, but it is easy to make mistakes. I think that when you just start contacting programming, especially C / C and Java, how much may have made the following or several types: 3 for statement The order of expression is wrong; the second expression logic is determined incorrect (missing some, more, even dead loops); forget mobile cursors; accidentally change the position of the cursor in the circulation body, etc. Why can't you let the compiler help us deal with these details? In 5.0, we can write this: Public void showall (Collection C) { For (Object Obj: c) { System.out.println (String) OBJ); } } Public void showall (String [] sa) { FOR (String str: sa) { System.out.println (STR); } } Such a code looks clearer and concise, isn't it? The specific syntax is simple: use ":" to separate, the front part is written from the type of type that will be taken from the array or Collection, and the name of the temporary variable, the rear part writes an array or Collection's reference. Plus generics, we can even make the first method more beautiful: Public Void Showall (Collection For (String Str: CS) { System.out.println (STR); } } Have you found: When you need to replace the Collection For this very convenient new language element, you will look very much away when you need to access the tag in the cyclic body: For example, when we handle a list, you need to update one of the elements, or delete an element, etc. Wait. At this time, you can't get the cursor information you need in the cyclic body, so you need to fall back to the original approach. However, with generic and enhanced For loops, we don't have to worry about the expression and nest of those who are annoying for the annoying for cycling. After all, we will not need to understand the specific location of the cursor, we only need to traverse an array or collection, right? 1.6. Automatic packing / automatic unpacking The so-called packing is to package the value type with the reference type of the reference type, so that they can have the identity of the object. If we can pack the INT type into an object of the Integer class, or package the double to double, and so on. The so-called unpacking is in contrast to the direction of the box, re-simplifies the object of the reference type of Integer and Double to the value type data. Before J2SE (TM) 5.0 is released, we can only handle the box and unpacking. Maybe you will ask, why do you need to pack and remove it? For example, when we try to add a value type of data to a collection, you need to put it first, because collection's add () method only accepts objects; and when we need to take this data later And when you want to operate using the value type it, we need to unpack it into a version of the value. Now, the compiler can help us complete these necessary steps. The following code I have two versions of the boxes and unpack, one version uses manual way, another version handles these obvious code to the compiler to complete: Public Static Void ManualBoxingunboxing (INT I) { ArrayList Alist.Add (0, New Integer (i)); Int a = alist.get (0) .intValue (); System.out.println ("THE VALUE OF I IS" A); } Public static void autoboxingunboxing (int i) { ArrayList Alist.Add (0, i); INT a = alist.get (0); System.out.println ("THE VALUE OF I IS" A); } See it, in J2SE (TM) 5.0, we no longer need to explicitly convert a value type of data into a corresponding object, thereby transmitting it as an object to other methods, and does not have to manually send that represents one Numerical objects are removed as the corresponding value type data, as long as you provide enough to make the compiler to believe that these packing / unpacking types are legal: For example, if we are in the code, if we Used is not arraylist Of course, you need enough attention to: On the one hand, there is a considerable difference from the value type and reference type, there is a considerable difference in the occupation of resources; on the other hand, the boxes and unboxes will bring additional overhead. While using this convenient feature, don't forget that these hidden people may affect performance. 1.7. Type security enumeration Before introducing the type of security enumeration introduced in J2SE (TM) 5.0, I would like to briefly introduce the background of this topic. We know that in C, we can define an enumeration type to use the alias to replace different elements in a collection, usually used to describe those categories or finite numbers or concepts, such as months, colors , Playing cards, solar planets, five continents, four oceans, seasons, disciplines, four operators, and so on. They usually look like this: Typedef enum {Spring, Summer, Autumn, Winter} Season; essentially, these alias are processed into int constant, such as 0 represents Spring, 1 represents Summer, and so on. Because these aliases are ultimately Int, so you can conduct four operations, which causes the language unclear. Java did not consider the concept of introducing enumeration, perhaps out of the Java language concise consideration, but using Java's major developers did not disappear because Java itself did not provide because Java itself disappeared, so there were some common Suitable for Java enumeration design patterns, such as Int Enum and TypeSafe Enum, there are many open source enumeration APIs and non-open source internal implementation. I roughly tell the int enum mode and TypeSafe Enum mode. The so-called int enum mode is to imitate the implementation of Enum in C, such as: Public class season { Public static final int SPRING = 0; Public static final int summer = 1; Public static final int autumn = 2; Public static final int winter = 3; } This mode is not much in the case of the enumeration in C, and the limit of C enumeration is basically. And TypeSafe Enum mode is much more robust: Public class season { PRIVATE FINAL STRING NAME; Private season (String name) { THIS.NAME = Name; } Public string toString () { Return Name; } Public Static Final Season Spring = New Season ("Spring"); Public Static Final Season Summer = New Season ("SUMMER"); Public Static Final Season Autumn = New Season ("Autumn"); Public Static Final Season Winter = New Season ("Winter"); } The latter implementation first prevents the inheritance and explicit instantiation of this class through the private construction method, so we can only get the four Season Categories, and provide a convenient TSTRING () method to get meaningful description And because this is a full-meaning class, we can easily join your own methods and logic from defining our enumeration classes. In the end, Java decided to hug enumeration, in J2SE (TM) 5.0, we saw this change, the design idea it used is basically the TypeSafe Enum mode mentioned above. Its syntax is simple, with an actual example, to define an enumeration, we can write this: Public Enum Language {Chinese, English, French, hungarian} Next we can use Language.english to use. Hey ... this example is a little too little child, let's look at an example of a complex point. Using Java's type security enumeration, we can define a public interface for all enumeration elements, and then specifically to each element itself, you can implement some specific behaviors for these interfaces. This will be quite convenient for those that can be classified, but also hope to access through unified interface. Usually, in order to achieve similar functions, we need to maintain a set of inheritance or similar enumeal patterns. An example of this Java official website here: public enum operation { Plus {Double Eval (Double X, Double Y) {Return X Y;}}, Minus {Double Eval (Double X, Double Y) {Return X - Y;}}, Times {Double Eval (double x, double y) {return x * y;}}, Divide {Double Eval (double x, double y) {return x / y;}}; // do arithmetic op report Represented by this constant Abstract Double Eval (Double X, Double Y); } In this enumeration, we define four elements, respectively correspond to the additional and subtraction, for each operation, we can invoke the evAl () method, and the specific method achieves different. We can test the following category by the following code: Public static void main (string args []) { Double x = double.parsedouble (args [0]); Double y = double.parsedouble (args [1]); For (Operation Op: Operation.values ()) { System.out.println (x "" OP "" Y "=" OP.EVAL (X, Y)); } } How, use an enumeration, is we very convenient to implement some interesting features? In fact, the type of Java's type of security is a class containing a limited number of generated own instances, which can be obtained by a class static field. 1.8. Variable length parameters As the name suggests, variable length parameters refer to the parameter body of the method, as long as it is defined, we can use any number of parameters, similar to the use of arrays. In J2SE (TM) 5.0, a new syntax is introduced, which is added "..." after the parameter type name, indicating that the method can accept multiple parameters of this type. It should be noted that the variable length parameters must be placed at the end of the parameter list, and one method can only contain one such parameters. Inside the method body, such parameters are treated as an array, it seems that the code should look like this: Public String Testvararg (String ... args) { Stringbuilder SB = New StringBuilder (); For (String str: args) { Sb.append (str); } Return sb.toString (); } Such method signatures are written to TestVararg (String [] args) is: When calling, you no longer need to pass a wrapped string array, you only need to write a series of string parameters, separated by commas However, it is like this method just having an overloaded version to accept that multiple String parameters. 1.9. Static introduction The so-called static introduction means that we now have a choice in addition to the introduction of classes: introducing a static field of a class. Such as: Import static java.lang.math.pi; or Import static java.lang.math. *; This way we are in the next code, when we need to use a static field that is introduced, you don't have to write the previous class name. Of course, when the name conflict occurs, the original class is introduced, or the prefix is required to distinguish. I personally think that this new language element is not significant. When you introduce too many static fields, the code will become difficult to read and maintain. Since the name of the static field is usually not as descriptive, I think it is a better choice to write a class name before the static field. However, after all, everyone's preferences and demand are different. If you think it is useful to you, since it is provided, then use it. 1.10. Metadata (annotation) Note is an important language element introduced by J2SE (TM) 5.0. Its corresponding JSR is JSR 175, let's take a look at the document pair annotation of JSR 175: Note does not directly affect the semantics of the program, while developing and deploying tools, you can read these annotations, processed, such as generating additional Java source code, XML documents, or other objects that will be used with the annotated program . In the previous J2SE version, we have already used a part of the early annotations such as @DepRecated, etc. These elements are usually used to generate HTML Javadoc. In J2SE (TM) 5.0, the annotations are officially introduced and pushed to the unprecedented height of Java history. Now, annotations are not only used to generate Javadoc, more importantly, annotations make the code compile time check more effective and convenient, and also enhance the code's ability to describe. Some annotations are released with J2SE (TM) 5.0, we can use it directly. In addition, we can easily achieve custom annotations. On this basis, many of us before we can only be completed by reflective mechanisms. What are our useful annotations to see the university: The first is @OVERRIDE, this annotation is used in the method, indicating that this method inherits from its parent class, so that this method can be very convenient to avoid we are not careful when we rewrite the method of rewriting inherited. The method is signed and quietly slipped through the compiler, causing a bug with a high concealed. Secondly @Deprecated, indicating that the item (class, field, method) is no longer recommended. There is also an @suppresswarnings, indicating that the range covered by this (class, field, method) does not need to display all warning information. This annotation needs to provide parameters, such as unchecked, and more. Below I explain to you through an example: the usage of these ready-made annotations: Public class main { @DepRecated Public String Str; Public static void main (String [] args) { New Submain (). DOSMETHING (); } Public void dosomething () { System.out.println ("DONE."); } Class Submain Extends Main { @Override @Suppresswarnings ("Unchecked", "Warning") Public void dosomething () { Java.util.Arraylist alist = new java.util.arrayList (); Alist.add (new integer (0)); System.out.println ("DONE BY SUBMAIN."); } } Of course, we can also write your own annotations. The syntax defined by the annotation is the @Interface keyword. J2SE (TM) 5.0 supports three forms of annotations: non-parameter marking annotations, with a parameter annotation and a complete annotation with multiple parameters. The following exemplifies: Tag annotation, similar @Deprecated, such as: @interface someemptyannotation {} Note from a single parameter, such as: @Interface mysingleelementannotation { String value (); } And the annotations of multiple parameters, such as: @Interface myannotationformethods { Int index (); String info (); String Developer () Default "Sean Gao"; } We can see that the definition of the annotation is quite similar to the definition of Interface, and we can also specify the default value. For these annotations, we can also add an annotation, so-called "annotation." For example, we usually use @Target to specify an annotation object, and the level, such as source code, class file, and so on with @Retrion. for example: @Target (ElementType.Method) @RetionPolicy.Source Public @Interface sign { } In use, we need to write @ before the annotation name, then specify parameter values, such as: @MYANNOTATIONFORMETHODS INDEX = 1, INFO = "this is a method to test myannotation.", Developer = "Somebody Else" ) Public void testmethod1 () { // ... } The biggest role of the annotation is that it adds useful information on the basis of the source code so that the descriptive of the source code is stronger. This information can be identified by tools other than the code, so that external functions can be easily increased, as well as reducing the maintenance of unnecessary related code / files. Here I want to brief a topic that exceeds J2SE (TM) 5.0: There is a considerable amount of annotations in the future EJB 3.0 specification, let us preview what will be defined by the future stateless session bean Sample: @StateLess Public Class BookshelfmanagerBean { Public void addbook (book abook) { // Business logic goes here ... } Public Collection getAllBooks () { // business logic goes here ...} // ... } We don't even have to write any interfaces and deployment descriptors, which will be completely completed by the external tools by reading the reflection, this is not very good? 1.11. C style formatted output Java has also had a Printf () style similar to C, which is also called Printf (), which relies on the variable length parameters mentioned in front. For example, we can write now: System.out.printf ("% s Has a value of% d.% N", someString, a); How, look good? It should be noted that Java adds the% N flag to the support of the multi-platform, which is supplemented with / N. For specific syntax for Java formatted output, please refer to the API documentation of Java.util.Formatter. 1.12. Conclusion In this introductory article, we went to the new language elements brought by J2SE 5.0. I don't know if everyone is also the same as the author, I feel these new features in improving our development efficiency. In fact, it is not just a language element, and J2SE (TM) 5.0 is released in many other aspects, including virtual machines, new API libraries, etc., performance and function have greatly improved. For friends who are primarily relying on J2EE, maybe try to make full use of these new elements in the work, I am afraid that the mainstream J2EE server supports J2EE (TM) 5.0, I am full of expectations. Author Blog: http://blog.9cbs.net/zhoubin_java/ related articles 55 kinds of webpages common tips (JavaScript) Java Common Questions Collection 25 Ask the Java programmer Interview 32, ask how many questions? J2SE 5.0 language features Generate a Java-prepared executable