本文介绍的java 7新特性更多的感觉像是语法糖。毕竟java本身已经比较完善了,不完善的很多比较难实现或者是依赖于某些底层(例如操作系统)的功能。不过java7也实现了类似aio的强大功能。但本文并未有此介绍。主要是 1.switch可以接受string类型而不像以前仅仅是int;2.异常catch可以一次处理完而不像以前一层层的surround;3.泛型类实例化也不用繁琐的将泛型声明再写一遍;4.文件读写 会自动关闭流而不像以前那样需要在finally中显式close;5.数值可以使用下划线分隔;6.文件读写功能增强,有更简单的api调用;7.文件改变的事件通知功能;8.多核 并行计算的支持加强 fork join 框架;9.还有一些动态特性的加入。
具体看代码:
1.switch可以接受string类型而不像以前仅仅是int;
- publicvoidprocessTrade(Tradet){
- Stringstatus=t.getStatus();
- switch(status){
- caseNEW:
- newTrade(t);
- break;
- caseEXECUTE:
- executeTrade(t);
- break;
- casePENDING:
- pendingTrade(t);
- break;
- default:
- break;
- }
- }
- publicvoidnewMultiCatch(){
- try{
- methodThatThrowsThreeExceptions();
- }catch(ExceptionOne|ExceptionTwo|ExceptionThreee){
- //loganddealwithallExceptions
- }
- }
3.泛型类实例化也不用繁琐的将泛型声明再写一遍;
- Map<String,List<Trade>>trades=newTreeMap<>();
4.文件读写 会自动关闭流而不像以前那样需要在finally中显式close;
- publicvoidnewTry(){
- try(FileOutputStreamfos=newFileOutputStream("movies.txt");
- DataOutputStreamdos=newDataOutputStream(fos)){
- dos.writeUTF("Java7BlockBuster");
- }catch(IOExceptione){
- //logtheexception
- }
- }
5.数值可以使用下划线分隔;
- intmillion=1_000_000
6.文件读写功能增强,有更简单的api调用;
- publicvoidpathInfo(){
- Pathpath=Paths.get("c:\\Temp\\temp");
- System.out.println("NumberofNodes:"+path.getNameCount());
- System.out.println("FileName:"+path.getFileName());
- System.out.println("FileRoot:"+path.getRoot());
- System.out.println("FileParent:"+path.getParent());
- //这样写不会抛异常
- Files.deleteIfExists(path);
- }
7.文件改变的事件通知功能;
- /**
- *Thisinitiatesthepolice
- */
- privatevoidinit(){
- path=Paths.get("C:\\Temp\\temp\\");
- try{
- watchService=FileSystems.getDefault().newWatchService();
- path.register(watchService,ENTRY_CREATE,ENTRY_DELETE,
- ENTRY_MODIFY);
- }catch(IOExceptione){
- System.out.println("IOException"+e.getMessage());
- }
- }
- /**
- *Thepolicewillstartmakingrounds
- */
- privatevoiddoRounds(){
- WatchKeykey=null;
- while(true){
- try{
- key=watchService.take();
- for(WatchEvent<?>event:key.pollEvents()){
- Kind<?>kind=event.kind();
- System.out.println("Eventon"+event.context().toString()+"is"+kind);
- }
- }catch(InterruptedExceptione){
- System.out.println("InterruptedException:"+e.getMessage());
- }
- booleanreset=key.reset();
- if(!reset)
- break;
- }
- }
8.多核 并行计算的支持加强 fork join 框架;
- ForkJoinPoolpool=newForkJoinPool(numberOfProcessors);
- publicclassMyBigProblemTaskextendsRecursiveAction{
- @Override
- protectedvoidcompute(){
- ...//yourprobleminvocationgoeshere
- }
- }
- pool.invoke(task);
9.还有一些动态特性的加入。
java.lang.invoke
包的引入。MethodHandle
,CallSite
还有一些其他类供使用。
具体参见原文 http://radar.oreilly.com/2011/09/java7-features.html
更多内容,大家可参考: