---
title: "Java7新特性（一）"
author: "txidol"
date: "2013-11-21T14:02:00Z"
tags: []
categories: ["编程语言"]
slug: "java7"
draft: false
lastmod: "2013-11-21T14:10:08Z"
id: 1978418
url: "https://txidol.iteye.com/blog/1978418"
---

#### 1.语法糖 数字下划线

```
package com.java7developer.chapter1;

import java.util.Collection;
import java.util.HashMap;

public class Coin {
	int test = 123_567; 
	long test1 = 100_000L; 
}
```

#### 2.switch语句中的String

```
public void printDay(String dayOfWeek){
    case "Sunday":System.out.println("ddd");break;
    default:System.out.println("sss");break;
}
```

 

#### 3.multicatch

```
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 iox) {
      System.err.println("Error while processing file '" + fileName + "'");
    }

    return cfg;
  }
```

 

#### 4.final重抛

对比上份代码

```
try {
      String fileText = getFile(fileName);
      cfg = verifyConfig(parseConfig(fileText));
    } catch (final Exception  e) {
      throw e;
    }
```

 

#### 5.try-with-resources(TWR) AutoCloseable

```
package com.java7developer.chapter1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Java7ResourcesExample {

  private void run() throws IOException {
    File file = new File("foo");
    URL url = null;
    try {
      url = new URL("http://www.google.com/");
    } catch (MalformedURLException e) {
    }

    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);
      }
    }
  }

  public static void main(String[] args) throws IOException {
    Java7ResourcesExample instance = new Java7ResourcesExample();
    instance.run();
  }

}
```

 

#### 6.钻石语法

```
HashMap<String, String> a = new HashMap<>();
```

 

#### 7.变参 消失的警告 @SafeVarargs

```
ublic class Coin {
	int test = 123_567; 
	long test1 = 100_000L;
	
	@SafeVarargs
	public static <T> Collection<T> doSomething(T... entries){
		return null;
	}
	
	public static void main(String[] args) {
		HashMap<String, String> a = new HashMap<>();
		HashMap<String, String> b = new HashMap<>();
		doSomething(a,b);
	}
}
```