java7 新特性 总结版

来源:互联网 发布:严格规定国家秘密的知 编辑:程序博客网 时间:2024/06/05 04:50

Java7语法新特性:


前言,这是大部分的特性,但还有一些没有写进去,比如多核 并行计算的支持加强 fork join 框架;这方面并没有真正写过和了解。也就不写进来了。


1. switch中增加对String类型的支持。

Java代码  收藏代码
    public String generate(String name, String gender) {         String title = "";         switch (gender) {             case "男":                 title = name + " 先生";                 break;             case "女":                 title = name + " 女士";                 break;             default:                 title = name;         }         return title;  



编译器在编译时先做处理:
①case只有一种情况,直接转成if;
②如果只有一个case和default,则直接转换为if...else...;
③有多个case,先将String转换为hashCode,然后对应的进行处理,JavaCode在底层兼容Java7以前版本。

2. 数字字面量的改进
①增加二进制表示
Java7前支持十进制(123)、八进制(0123)、十六进制(0X12AB)
Java7增加二进制表示(0B11110001、0b11110001)
②数字中可添加分隔符
Java7中支持在数字量中间增加'_'作为分隔符,更直观,如(12_123_456),下划线只能在数字中间,编译时编译器自动删除数字中的下划线。

3. 异常处理
①Throwable类增加addSuppressed方法和getSuppressed方法,支持原始异常中加入被抑制的异常。
异常抑制:在try和finally中同时抛出异常时,finally中抛出的异常会在异常栈中向上传递,而try中产生的原始异常会消失。
在Java7之前的版本,可以将原始异常保存,在finally中产生异常时抛出原始异常:
Java代码  收藏代码
    public void read(String filename) throws BaseException {          FileInputStream input = null;          IOException readException = null;          try {              input = new FileInputStream(filename);          } catch (IOException ex) {              readException = ex;   //保存原始异常          } finally {              if (input != null) {                  try {                      input.close();                  } catch (IOException ex) {                      if (readException == null) {                          readException = ex;                      }                  }              }              if (readException != null) {                  throw new BaseException(readException);              }          }      }  


在Java7中的版本,可以使用addSuppressed方法记录被抑制的异常:
Java代码  收藏代码
    public void read(String filename) throws IOException {          FileInputStream input = null;          IOException readException = null;          try {              input = new FileInputStream(filename);          } catch (IOException ex) {              readException = ex;          } finally {              if (input != null) {                  try {                      input.close();                  } catch (IOException ex) {                      if (readException != null) {    //此处的区别                          readException.addSuppressed(ex);                      }                      else {                          readException = ex;                      }                  }              }              if (readException != null) {                  throw readException;              }          }      }  


②catch子句可以同时捕获多个异常
Java代码  收藏代码
    public void testSequence() {          try {              Integer.parseInt("Hello");          }          catch (NumberFormatException | RuntimeException e) {  //使用'|'分割,多个类型,一个对象e                       }      }  


③try-with-resources语句
Java7之前需要在finally中关闭socket、文件、数据库连接等资源;
Java7中在try语句中申请资源,实现资源的自动释放(资源类必须实现java.lang.AutoCloseable接口,一般的文件、数据库连接等均已实现该接口,close方法将被自动调用)。

Java代码  收藏代码
     public void read(String filename) throws IOException {           try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {               StringBuilder builder = new StringBuilder();      String line = null;      while((line=reader.readLine())!=null){          builder.append(line);          builder.append(String.format("%n"));      }      return builder.toString();           }        }  



try子句中可以管理多个资源:
Java代码  
  1. public void copyFile(String fromPath, String toPath) throws IOException {       try ( InputStream input = new FileInputStream(fromPath);      OutputStream output = new FileOutputStream(toPath) ) {           byte[] buffer = new byte[8192];  int len = -1;  while( (len=input.read(buffer))!=-1 ) {      output.write(buffer, 0, len);  }       }    }  



4. 变长参数方法的优化
Java7之前版本中的变长参数方法:
Java代码  收藏代码
    public int sum(int... args) {          int result = 0;          for (int value : args) {              result += value;          }          return result;      }  


对collections的支持

Java代码

List<String> list = new ArrayList<String>();        list.add("item");       String item = list.get(0);                Set<String> set = new HashSet<String>();        set.add("item");                Map<String, Integer> map = new HashMap<String, Integer>();        map.put("key", 1);        int value = map.get("key");     


 

 现在你还可以:

    List<String> list = ["item"];           String item = list[0];                      Set<String> set = {"item"};                       Map<String, Integer> map = {"key" : 1};           int value = map["key"];     


2.自动资源管理

原来:

    BufferedReader br = new BufferedReader(new FileReader(path));            try {              return br.readLine();            } finally {               br.close();            }      

现在:

    try (BufferedReader br = new BufferedReader(new FileReader(path)) {                return br.readLine();             }                          //You can declare more than one resource to close:                          try (               InputStream in = new FileInputStream(src);                OutputStream out = new FileOutputStream(dest))            {             // code            }      


3.对通用实例创建(diamond)的type引用进行了改进

原来:

    Map<String, List<String>> anagrams = new HashMap<String, List<String>>();   


现在:

    Map<String, List<String>> anagrams = new HashMap<>();    


4.数值可加下划线

    int one_million = 1_000_000;    


6.二进制文字

int binary = 0b1001_1001;  


异常catch可以一次处理完而不像以前一层层的surround;

public void newMultiCatch() {               try {                     methodThatThrowsThreeExceptions();               } catch (ExceptionOne | ExceptionTwo | ExceptionThree e) {                     // log and deal with all Exceptions               }         }  

文件读写 会自动关闭流而不像以前那样需要在finally中显式close;

public void newTry() {                  try (FileOutputStream fos = new FileOutputStream("movies.txt");                          DataOutputStream dos = new DataOutputStream(fos)) {                    dos.writeUTF("Java 7 Block Buster");              } catch (IOException e) {                    // log the exception              }        }  




1 0