jdk1.5新特性

“JDK1.5”(開發代號猛虎)的一個重要主題就是通過新增一些特性來簡化開發,這些特性包括泛型,for-each 循環,自動裝包/拆包,枚舉,可變參數, 靜態導入。使用這些特性有助於我們編寫更加清晰,精悍,安全的代碼。

 

下面我們簡單介紹一下這些新特性。

 

 

1、泛型:泛型、通配符、有限制通配符、泛型方法

 

2、加強循環

 

3、 自動裝箱/拆箱

 

4、枚舉

 

5、可變參數

 

6、靜態引入

 

7、元數據

 

8、 控制檯輸入

 

9、改變返回類型

 

10、格式化I/O1.泛型(Generic)

 

 

 

1.泛型

C++通過模板技術可以指定集合的元素類型,而Java在1.5之前一直沒有相對應的功能。一個集合可以放任何類型的對象,相應地從集合裏面拿對象的時候我們也不得不對他們進行強制得類型轉換。猛虎引入了泛型,它允許指定集合裏元素的類型,這樣你可以得到強類型在編譯時刻進行類型檢查的好處。

Collection<String> c = new ArrayList();

c.add(new Date());

編譯器會給出一個錯誤,

add(java.lang.String) injava.util.Collection<java.lang.String> cannot be applied to(java.util.Date)

 

 

2.For-Each循環

For-Each循環得加入簡化了集合的遍歷。假設我們要遍歷一個集合對其中的元素進行一些處理。典型的代碼爲:

void processAll(Collection c){

for(Iterator i=c.iterator(); i.hasNext(){

MyClass myObject = (MyClass)i.next();

myObject.process();

}

}

使用For-Each循環,我們可以把代碼改寫成,

void processAll(Collection<MyClass>c){

for (MyClass myObject :c)

myObject.process();

}

這段代碼要比上面清晰許多,並且避免了強制類型轉換。

 

 

3.自動裝包/拆包(Autoboxing/unboxing)

自動裝包/拆包大大方便了基本類型數據和它們包裝類地使用。

自動裝包:基本類型自動轉爲包裝類.(int >> Integer)

自動拆包:包裝類自動轉爲基本類型.(Integer >> int)

在JDK1.5之前,我們總是對集合不能存放基本類型而耿耿於懷,現在自動轉換機制解決了我們的問題。

int a = 3;

Collection c = new ArrayList();

c.add(a);//自動轉換成Integer.

 

Integer b = new Integer(2);

c.add(b + 2);

這裏Integer先自動轉換爲int進行加法運算,然後int再次轉換爲Integer.

 

 

4.枚舉(Enums)

JDK1.5加入了一個全新類型的“類”-枚舉類型。爲此JDK1.5引入了一個新關鍵字enmu.我們可以這樣來定義一個枚舉類型。

 

public enum Color

{

Red,

White,

Blue

}

然後可以這樣來使用Color myColor = Color.Red.

枚舉類型還提供了兩個有用的靜態方法values()和valueOf(). 我們可以很方便地使用它們,例如

for (Color c : Color.values())

System.out.println(c);

 

5.可變參數(Varargs)

可變參數使程序員可以聲明一個接受可變數目參數的方法。注意,可變參數必須是函數聲明中的最後一個參數。假設我們要寫一個簡單的方法打印一些對象,

util.write(obj1);

util.write(obj1,obj2);

util.write(obj1,obj2,obj3);

在JDK1.5之前,我們可以用重載來實現,但是這樣就需要寫很多的重載函數,顯得不是很有效。如果使用可變參數的話我們只需要一個函數就行了。一個方法只能定義一個可變參數

 

//取值方法

public void write(Object... objs) {

for (Object obj: objs)

System.out.println(obj);

}

 

// 取值方法定義一個list變量variabledeclaration

 

 

 

private list features;

 

 

 

// assignment in method or constructor body

 

 

 

this.features =java.util.arrays.aslist(objs);

 

 

在引入可變參數以後,Java的反射包也更加方便使用了。對於c.getMethod("test", new Object[0]).invoke(c.newInstance(),new Object[0])),

現在我們可以這樣寫了c.getMethod("test").invoke(c.newInstance()),這樣的代碼比原來清楚了很多。

 

 

6.靜態導入(Static Imports)

要使用用靜態成員(方法和變量)我們必須給出提供這個方法的類。使用靜態導入可以使被導入類的所有靜態變量和靜態方法在當前類直接可見,使用這些靜態成員無需再給出他們的類名。

import static java.lang.Math.*;

…….

r = sin(PI * 2); //無需再寫r =Math.sin(Math.PI); 

 

The For-Each Loop Language Contents

 

 

--------------------------------------------------------------------------------

Iterating over a collection is uglier thanit needs to be. Consider the following method, which takes a collection oftimer tasks and cancels them:

void cancelAll(Collection<TimerTask>c) {

for (Iterator<TimerTask> i =c.iterator(); i.hasNext(); )

i.next().cancel();

}

 

The iterator is just clutter. Furthermore,it is an opportunity for error. The iterator variable occurs three times ineach loop: that is two chances to get it wrong. The for-each construct gets ridof the clutter and the opportunity for error. Here is how the example lookswith the for-each construct:

 

void cancelAll(Collection<TimerTask>c) {

for (TimerTask t : c)

t.cancel();

}

 

When you see the colon (:) read it as “in.”The loop above reads as “for each TimerTask t in c.” As you can see, thefor-each construct combines beautifully with generics. It preserves all of thetype safety, while removing the remaining clutter. Because you don't have todeclare the iterator, you don't have to provide a generic declaration for it.(The compiler does this for you behind your back, but you need not concernyourself with it.)

 

Here is a common mistake people make whenthey are trying to do nested iteration over two collections:

 

List suits = ...;

List ranks = ...;

List sortedDeck = new ArrayList();

 

// BROKEN - throws NoSuchElementException!

for (Iterator i = suits.iterator();i.hasNext(); )

for (Iterator j = ranks.iterator();j.hasNext(); )

sortedDeck.add(new Card(i.next(),j.next()));

 

Can you spot the bug? Don't feel bad if youcan't. Many expert programmers have made this mistake at one time or another.The problem is that the next method is being called too many times on the“outer” collection (suits). It is being called in the inner loop for both theouter and inner collections, which is wrong. In order to fix it, you have toadd a variable in the scope of the outer loop to hold the suit:

 

// Fixed, though a bit ugly

for (Iterator i = suits.iterator();i.hasNext(); ) {

Suit suit = (Suit) i.next();

for (Iterator j = ranks.iterator();j.hasNext(); )

sortedDeck.add(new Card(suit, j.next()));

}

 

So what does all this have to do with thefor-each construct? It is tailor-made for nested iteration! Feast your eyes:

 

for (Suit suit : suits)

for (Rank rank : ranks)

sortedDeck.add(new Card(suit, rank));

 

The for-each construct is also applicableto arrays, where it hides the index variable rather than the iterator. Thefollowing method returns the sum of the values in an int array:

 

// Returns the sum of the elements of a

int sum(int[] a) {

int result = 0;

for (int i : a)

result += i;

return result;

}

 

So when should you use the for-each loop?Any time you can. It really beautifies your code. Unfortunately, you cannot useit everywhere. Consider, for example, the expurgate method. The program needsaccess to the iterator in order to remove the current element. The for-eachloop hides the iterator, so you cannot call remove. Therefore, the for-eachloop is not usable for filtering. Similarly it is not usable for loops whereyou need to replace elements in a list or array as you traverse it. Finally, itis not usable for loops that must iterate over multiple collections inparallel. These shortcomings were known by the designers, who made a consciousdecision to go with a clean, simple construct that would cover the greatmajority of cases.

 

7.元數據

 

元數據,在java中也叫註釋、註解。微軟的.net從開始設計時就有這個功能,不過它的術語叫屬性。

在將來的j2ee開發中,廣泛的使用它,包括ejb的聲明,IOC中的注入等。

 

元數據,在java中也叫註釋、註解。微軟的.net從開始設計時就有這個功能,不過它的術語叫屬性。

 

這時一個強大的功能,程序員如果想掙錢,得好好研究它,因爲

 

在將來的j2ee開發中,廣泛的使用它,包括ejb的聲明,IOC中的注入等。

 

 

IBM網站有篇文章詳細介紹了它,挺好的一篇文章。

 

http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/

 

http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml

 

 

 

我曾興致勃勃的根據例子在eclipse中測試了一把,可怎麼也得不到註釋信息。後來,在命令行直接編譯java文件,運行才正常。雖然現在的eclipse 編輯器可以識別java的註釋語法,但是在編譯的時候並沒有生成帶註釋的java類。我沒有仔細深究,可能時eclipse在編譯的時候枚加上-target 5參數吧,猜測而已。

 

新建一個註釋類型,這個類型指明瞭一本名著的作者和他的email。

 

   package com.kuaff.jdk5;

     

   import java.lang.annotation.*;

     

   @Retention(RetentionPolicy.RUNTIME)

   @Target(ElementType.METHOD)

   public @interface BookAuthor 

    {

       String name(); 

          String email();

    }

     

     

 

 

使用這個註釋爲我們的方法加上註解:

 

   package com.kuaff.jdk5;

     

   import java.lang.annotation.Annotation;

     

   public class MetadataShow

    {

        @BookAuthor(name="曹雪芹",email="[email protected]") 

       public void introHongLouMeng()

        {

           System.out.println("這是一本好書啊");

        }

     

       public static void main(String[] args)

        {

            MetadataShow metadata = new MetadataShow();

           try

            {

                Annotation[] annotation =metadata.getClass().getMethod("introHongLouMeng").getAnnotations();

                for(Annotation   a : annotation)

                 {

                    System.out.printf("作者:%s%n",((BookAuthor)a).name());

                    System.out.printf("他的電子郵件(可能已被註銷):%s%n",((BookAuthor)a).email());

                 }

            }

           catch (SecurityException e)

            {

                 e.printStackTrace();

            }

           catch (NoSuchMethodException e)

            {

                 e.printStackTrace();

            }

        }

    }

     

      

 

請注意,要想在程序運行時能讀取這些註釋,需要在註釋的聲明的時候加上

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD) //也可能時其他類型,如針對聲明的註釋

 

這是對註釋的註釋。

編譯這兩個文件:

javac-source 5 -target 5 -d bin src/com/kuaff/jdk5/*.java


轉載自:http://blog.csdn.net/j2eeweiwei/article/details/3932775

發佈了29 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章