Java SE 7新增特效

9 篇文章 0 订阅

Java SE 7新增特效

目前生产环境是jdk7,以前都是用的jdk6,升到7,还是有些不错的特性,研究一下。

官方文档在这

Java Programming Language Enhancements 
Enhancements in Java SE 7 
Binary Literals - In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. 
Underscores in Numeric Literals - Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code. 
Strings in switch Statements - You can use the String class in the expression of a switch statement. 
Type Inference for Generic Instance Creation - You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. 
Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods - The Java SE 7 complier generates a warning at the declaration site of a varargs method or constructor with a non-reifiable varargs formal parameter. Java SE 7 introduces the compiler option -Xlint:varargs and the annotations @SafeVarargs and @SuppressWarnings({“unchecked”, “varargs”}) to supress these warnings. 
The try-with-resources Statement - The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the new java.lang.AutoCloseable interface or the java.io.Closeable interface can be used as a resource. The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement. 
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking - A single catch block can handle more than one type of exception. In addition, the compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

1. 二进制字面值(Binary Literals)

在java se 7里,整形(byte,short,int,long)类型的值可以用二进制类型来表示了,在使用二进制的值时,需要上ob或oB前缀

// 例子
byte aByte = (byte)0b00100001;
short aShort = (short)0b1010000101000101;
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101;
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

// 二进制同十进制和十六进制相比,可以一目了然的看出数据间的关系。下面的代码就展示的是移位操作
public static final int[] phases = {
0b00110001,
0b01100010,
0b11000100,
0b10001001,
0b00010011,
0b00100110,
0b01001100,
0b10011000
}
// 相比十六进制,没有二进制更了然
public static final int[] phases = {
0x31, 0x62, 0xC4, 0x89, 0x13, 0x26, 0x4C, 0x98
}
2. 数值中支持_(Underscores in Numeric Literals)

可以在数值中增加_,增加可读性 
但是下面四中情况,不能增加_

  • 数字的开头和结尾
  • 小数点前后
  • F或者L前
  • 不能把数值中出现的字符分开(比如不能用0_x111,0x_111)
// 不可以
float pi1 = 3_.1415F;
float pi2 = 3._1415F;
long socialSecurityNumber1 = 999_99_9999_L;
int x1 = _52;
int x3 = 52_;
int x5 = 0_x52;
int x11 = 052_;
int x6 = 0x_52;
int x8 = 0x52_;

// 可以
int x2 = 5_2;
int x4 = 5_______2;
int x7 = 0x5_2;
int x9 = 0_52;
int x10 = 05_2;
3. switch支持String类型(Strings in switch Statements)

每个case是使用String的equals方法来进行比较的,对大小写敏感

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
The switc
4. 推断泛型类型参数 (Type Inference for Generic Instance Creation)

只要编译器可以从上下文中推断出类型参数,你就可以用一对空着的尖括号<>来代替泛型参数

//java7之后
Map<String, List<String>> myMap = new HashMap<>();
//java7之前
Map<String, List<String>> myMap = new HashMap<String, List<String>>();

Java SE7 只支持有限的类型推断。 
只有构造器的参数化类型在上下文中被显著的声明了,你才可以使用类型推断,否则不行。

List<String> list = new ArrayList<>();
// 可以
list.add("A");
// 不可以
list.addAll(new ArrayList<>());
// 改成这样才可以
List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);
5. try-with-resources 描述(The try-with-resources Statement)

try-with-resources 是一个定义了一个或多个资源的try 声明.这个资源是程序处理完它之后需要关闭的对象。try-with-resources 确保每一个资源在处理完成后都会被关闭。 
任何实现了java.lang.AutoCloseable 接口和java.io.Closeable 接口的对象可以使用try-with-resources的资源。

static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}

由于BufferedReader定义在try-with-resources 声明里,无论try语句正常还是异常的结束,它都会自动的关掉。而在java7以前,你需要使用finally块来关掉这个对象。

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}

但是,如果 readLine() 和 close() 这两个方法都抛出异常,那么readFirstLineFromFileWithFinallyBlock 方法只会抛出后面部分也就是finally块中的内容,try块中的异常就被抑制了,对于我们的程序来说,这显然不是一种好的方式。 
而在java 7中,无论是try块还是try-with-resource中抛出异常,readFirstLineFromFile会捕捉到try块的异常,try-with-resources中异常会被抑制。在java 7 中,你能捕捉到被抑制的异常。后面会介绍。

另外,一个try-with-resourcse声明了可以包含多个对象的声明,用分号隔开,和声明一个对象相同,会在结束后自动调用close方法,调用顺序和生命顺序相反。

public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
throws java.io.IOException
{

java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

try (
java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// xxx
}
}
6. 捕获多个异常及增加类型检查后的重抛(Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking)
6.1 捕获多个异常

在Java SE7里,一个catch可以捕获多个异常,每个异常之间用 | 隔开。

// java se 7之前
catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}

// 之后
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}

注意,如果一个catch处理了多个异常,那么这个catch的参数默认就是final的,你不能在catch块里修改它的值。 
另外,用一个catch处理多个异常,比用多个catch每个处理一个异常生成的字节码要更小更高效。

6.2 使用更强的类型检查重抛异常

Java Se 7可以更准确的分析出你抛出的异常类型。可以在throws上抛出更加具体的异常类型

  static class FirstException extends Exception { }
static class SecondException extends Exception { }

public void rethrowException(String exceptionName) throws Exception {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e;
}
}

这个例子,try块中能抛出两种异常.在java SE7以前的版本中,在方法声明中throws 只能写Exception,因为catch里的类型是 Exception. 但是在java SE7及以后的版本中,可以在throws后面写 FirstException和SecondException——编译器能判断出throw e语句抛出的异常e 一定来自try块,并且try块只能抛出FirstException和SecondException。

  public void rethrowException(String exceptionName)
throws FirstException, SecondException
{
try {
// ...
}
catch (Exception e) {
throw e;
}
}

Java SE 7之后,当在catch块中声明一个活多个异常,并在catch块中重新抛出时,编译器会根据下述几个条件判断重抛的异常类型:

  • Try块里抛出它
  • 没有其他catch块处理它
  • 它是catch里一个异常类型的父类或子类。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值