java7新特性简单介绍

switch对字符串的支持

public class Client {
  public static void main(String[] args) {
    String name = "lisi";
    switch (name) {
      case "lisi":
        System.out.println(name);
        break;
      case "wangwu":
        System.out.println(name);
        break;
      case "zhangsan":
        System.out.println(name);
        break;
    }
  }
}

其实java编译器会帮我们转换成字符串的hashcode()

数字字面量改进

public class Client {
  public static void main(String[] args) {
//二进制支持
    int num1 = 0B1001;
    System.out.println(num1);
//支持加_
    num1 = 1_000_000;
    System.out.println(num1);
  }
}

编译器帮我们转成10进制,去掉_

try-with-resources语句

在try语句中申请资源,实现资源的自动释放,资源需要实现AutoCloseable接口,文件、数据库连接等都已实现。

public class Client {
  public static void main(String[] args) {
    try (ByteArrayInputStream bais = new ByteArrayInputStream("hello".getBytes());
         ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      int len = -1;
      while ((len = bais.read()) != -1) {
        baos.write(len);
      }
      System.out.println(new String(baos.toByteArray()));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

编译器会自动调用资源的close方法。

增强泛型推断

public class Client {
  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
  }
}

编译期会自动推断HashMap的类型

NIO2(AIO)的支持

public class Client {
  public static void main(String[] args) throws IOException {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel
        .open(Paths.get("D:\\Client.java"));
    fileChannel.read(ByteBuffer.allocate(4098), 0, "hello", new CompletionHandler<Integer, String>() {
      @Override
      public void completed(Integer result, String attachment) {
        System.out.println(result);
        System.out.println(attachment);
      }

      @Override
      public void failed(Throwable exc, String attachment) {
        System.out.println(exc);
        System.out.println(attachment);
      }
    });
  }
}

异步文件通道,在文件读取完成执行回调方法

JSR292与InvokeDynamic

JSR 292: Supporting Dynamically Typed Languages on the JavaTM Platform,支持在JVM上运行动态类型语言。在字节码层面支持了InvokeDynamic。具体请看这一篇

一些工具类

Files(操作文件的工具),Paths(操作文件路径的工具),Objects(操作对象的工具)

fork/join并行框架

Java7提供的一个用于并行执行任务的框架,是一个把大任务分割成若干个小任务,最终汇总每个小任务结果后得到大任务结果的框架。

posted @ 2020-07-22 22:33  strongmore  阅读(282)  评论(0编辑  收藏  举报