Java7的新特性1-project coin

Project coin

project coinJava一些語法改進的一個項目。 java

Strings in switch

Java1.7以前,switch語句只能是bytecharshortint以及包裝類和枚舉常量,好比: python

enum Days { 性能

    MONDAY("1"), this

    Tuesday("2"); url

    private String value; spa

    private Days(String value) { 日誌

        this.value = value; orm

    } 對象

    public String getValue() { 繼承

        return value;

    }

}

...

Days day = Days.MONDAY;

switch(day) {

    case MONDAY:

        System.out.println("1");

        break;

    case Tuesday:

        System.out.println("2");

        break;

    default:

        System.out.println("3");

        break;

}

Java7中,擴展了容許String類型,好比:

public static void printDay(String dayOfWeek) {

    switch (dayOfWeek) {

        case "Sunday":

            System.out.println("星期天,休息休息");

            break;

        case "Monday":

            System.out.println("週一,要上班了,哎...");

            break;

        case "Tuesday":

            System.out.println("次日,好無聊");

            break;

        case "Wednesday":

            System.out.println("第三天了,怎麼還不到週五");

            break;

        case "Thursday":

            System.out.println("要崩潰了");

            break;

        case "Friday":

            System.out.println("趕快下班吧,受不了了");

            break;

        case "Saturday":

            System.out.println("這麼晚了,又浪費了一天,那就再睡會兒吧");

            break;

        default:

            System.out.println("這是星期幾,哦這是火星了");

            break;

    }

}

Enhanced syntax for numeric literals

Java7以前,定義一個二進制數字,須要使用以下:

int x = Integer.parseInt("1100110", 2);

這樣不但冗長,並且性能也很差,Java7引入新的語法,定義二進制可使用以下方式:

x = 0b1011;

在定義很長的數字時,容易形成錯誤,Java7使用下劃線做爲分隔符來分割長數字以下:

long anotherLong = 2_147_483_648L;

int bitPattern = 0b0001_1100__0011_0111__0010_1011__1010_0011;

Improved exception handling

Java7對異常處理增長兩項特性:multicatchfinal rethrow。好比處理配置文件須要處理多項checked exception,好比:

public Configuration getConfig(String fileName) {

    Configuration cfg = null;

    try {

        String fileText = getFile(fileName);

        cfg = verifyConfig(parseConfig(fileText));

    } catch (FileNotFoundException fnfx) {

        System.err.println("Config file '" + fileName + "' is missing");

    } catch (IOException e) {

        System.err.println("Error while processing file '" + fileName + "'");

    } catch (ConfigurationException e) {

        System.err.println("Config file '" + fileName + "' is not consistent");

    } catch (ParseException e) {

        System.err.println("Config file '" + fileName + "' is malformed");

    }

    return cfg;

}

有時咱們須要對FileNotFoundException和ParseException同一進行處理,Java7可使用以下方式:

public Configuration getConfig(String fileName) {

    Configuration cfg = null;

    try {

        String fileText = getFile(fileName);

        cfg = verifyConfig(parseConfig(fileText));

catch (FileNotFoundException | ParseException |

 ConfigurationException e) {

        System.err.println("Config file '" + fileName + "' is missing  or malformed");

    } catch (IOException e) {

        System.err.println("Error while processing file '" + fileName + "'");

    } 

    return cfg;

}

有時咱們在捕獲異常時,進行相應錯誤日誌記錄後會從新拋出,好比:

try {

  doSomethingWhichMightThrowIOException();

  doSomethingElseWhichMightThrowSQLException();

} catch (Exception e) {

  ...

  throw e;

}

從新拋出的異常因爲類型爲Exception,由於可能會隱藏實際的異常類型,好比實際拋出的是IOExceptionJava7可使用在Exception前加final來告知實際拋出的異常:

try {

  doSomethingWhichMightThrowIOException();

  doSomethingElseWhichMightThrowSQLException();

} catch (final Exception e) {

  ...

  throw e;

}

Try-with-resources (TWR)

在處理IO的代碼中,咱們會使用大量的try...catch()...finally...語法,其中會在finally進行IOclose操做,寫過python的都知道,這種操做可使用try-with-resources操做,幸運的是Java7也有了此特性,好比以前的語法:

private void test(URL url, File file) {

    InputStream is = null;

    try {

        is = url.openStream();

        OutputStream out = new FileOutputStream(file);

        try {

            byte[] buf = new byte[4096];

            int len;

            while ((len = is.read(buf)) >= 0)

                out.write(buf, 0, len);

        } catch (IOException iox) {

        } finally {

            try {

                out.close();

            } catch (IOException closeOutx) {

            }

        }

    } catch (FileNotFoundException fnfx) {

    } catch (IOException openx) {

    } finally {

        try {

            if (is != null)

                is.close();

        } catch (IOException closeInx) {

        }

    }

}

而使用try-with-resources語法,則能夠簡化爲:

try (OutputStream out = new FileOutputStream(file); InputStream is = url.openStream()) {

    byte[] buf = new byte[4096];

    int len;

    while ((len = is.read(buf)) > 0) {

        out.write(buf, 0, len);

    }

}

可是使用try-with-resources的時候仍是由可能形成資源沒有關閉,好比在try()中有錯誤時,好比:

try ( ObjectInputStream in = new ObjectInputStream(new 

      FileInputStream("someFile.bin")) ) {

 ...

}

好比文件存在,但卻不是寫入的對象序列,所以會形成不正常打開,此時ObjectInputStream不能正確初始化,且不會關閉,所以正確的方式是分開資源變量:

try ( FileInputStream fin = new FileInputStream("someFile.bin");

         ObjectInputStream in = new ObjectInputStream(fin) ) {

 ...

}

TWR特性是使用了java7的新的接口AutoCloseable,可使用try-with-resources語法的資源必須實現該接口。而Closeable繼承了AutoCloseable,所以咱們經常使用的資源類均可以使用。

Diamond syntax

diamond syntax是用來簡化泛型的,好比:

Map<Integer, Map<String, String>> usersLists = 

    new HashMap<Integer, Map<String, String>>();

能夠簡化爲:

Map<Integer, Map<String, String>> usersLists = new HashMap<>();

相關文章
相關標籤/搜索