`
lirig
  • 浏览: 237621 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JDK7 新特征

    博客分类:
  • Jave
阅读更多

虽然是英文,还能看得懂,感觉变化了很大,用起来也简单多了!

Improved Type Inference

i. Constructors

The addition of generics to the language greatly improved compile time type checking and largely eliminated the need for casting.  Unfortunately it also increased the verbosity of declarations, for example:

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

As a result, generic declarations often require multiple lines. It would be nice if you could omit the second occurrence of the type parameters (<String, List<String>>) and let the compiler figure it out ("constructor type inference "). This would remove the redundancy from the declaration, geatly enhancing readability and ease-of-use:

    Map<String, List<String>> anagrams = new HashMap<>();//这个有意思!

See also  http://gafter.blogspot.com/2007/07/constructor-type-inference.html

ii. Argument Positions

The result of a generic method, such as:

    public <E> Set<E> emptySet() { ... }

may be used on the right-hand side of an assignment:

    Set<Person> honestPoliticians = Collections.emptySet();

The compiler's type-inference mechanism figures out that the type parameter to the  emptySet  invocation is  Person .  It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method:

    void timeWaitsFor(Set<Man> people) { ... }

       ...

    timeWaitsFor(Collections.emptySet());   // * Won't compile!

Sadly, this is not allowed.  The specification currently requires an  explicit type argument   under these circumstances:

    timeWaitsFor(Collections.<Man> emptySet());

Not only are explicit type arguments awkward, but many programmers are unfamiliar with them and unable to cope when the compiler requires them.  With inference in argument positions, the explicit type argument is rarely required and the starred method invocation above becomes legal.

See also  http://lampwww.epfl.ch/~odersky/ftp/local-ti.ps   and  http://www.javac.info/Inference.html

Enum Comparison

Enum constants can safely be compared for equality use the == operator.  All enum types implement Comparable, so it stands to reason that it should be possible to compare constants of an enumerated type for order using the <, >, <=, and >= operators.  Unfortunately, it isn't, so programmers are forced to litter their code with calls to the compareTo method:

    enum Size { SMALL, MEDIUM, LARGE }

    if (mySize.compareTo(yourSize) >= 0)

        System.out.println("You can wear my shirt.");

If the <, >, <=, and >= operators worked for enums, this code could be replaced by the clearer:

    if (mySize >= yourSize)

        System.out.println("You can wear my shirt.");

See also  http://www.javac.info/EnumCompare.html

String Switch

Information often comes into programs in string form, and some action (often translation into another form) takes place depending on the string value.  For example, the following method translates strings to boolean values:

     static boolean booleanFromString(String s) {
        if (s.equals("true")) {
            return true;
        } else if (s.equals("false")) {
            return false;
        } else {
            throw new IllegalArgumentException(s);
        }
     }

This code is not pretty, and somewhat bug-prone.  If it were possible to switch on string values, this code could be replaced by the prettier and safer:

//这个也比较爽!

     static boolean booleanFromString(String s) {
        switch(s) {
          case "true":
            return true;
          case "false":
            return false;
        }
        throw new IllegalArgumentException(s);
    }

See also  http://yost.com/computers/java/string-switch/index.html

Chained Invocations

Some mutation-based APIs have a number of methods that return void. This is common in the factory pattern:

    class Factory {

        void setSomething(Something something) { ... }

        void setOther(Other other) { ... }

        Thing result() { ... }

    }

Using such a class can be awkward

    Factory fac = new Factory();

    fac.setSomething(something);

    fac.setOther(other);
    Thing thing = fac.result();

With chained invocations, you can reuse the receiver of the previous invocation and chain the calls together:

//这个更加爽!

    Thing thing = new Factory()

        .setSomething(something)

        .setOther(other)

        .result();
With this language support, it is much easier to define "fluent" APIs.

See also  http://docs.google.com/View?docid=dg8rbgp8_0gnjwr2

Extension methods

Existing interfaces cannot be extended with additional methods without breaking some clients. Instead, functionality is typically "added to an interface" by static methods in a separate utility class. Using them is somewhat awkward:

    List<String> list = ...;

    Collections.sort(list);

With extension methods, client can designate utility methods to act as if they were members of the interface (or class)

    import static java.util.Collections.sort;

    list.sort();


See also  http://www.javac.info/ExtensionMethods.html

Improved Catch Clauses  

i. Catching Multiple Exception Types

It is often necessary to do the same thing when one of several exceptions occurs.  Currently the only way to do this is to duplicate code in multiple catch clauses:

    try {
        return klass.newInstance();
    } catch (InstantiationException e) {
        throw new AssertionError(e);
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);
    }

It may be tempting to replace several catch clauses with one for the class that is the "least common ancestor" of the each of the exception types in question:

    // Broken - catches exceptions that should be allowed to propagate!  

    try {
        return klass.newInstance();
    } catch (Exception e) {
        throw new AssertionError(e);
    }

Unfortunatley this does not have the correct semantics. In the case of this example, it erroneously wraps unchecked exceptions in assertion errors.  To solve this problem, we propose that it be possible to catch two or more exception types in a single catch clause:

    try {
        return klass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new AssertionError(e);
    }


See also  http://www.javac.info/Multicatch.html

ii. Improved Checking for Rethrown Exceptions

It is not uncommon that you want to catch an exception, perform some action, and rethrow the exception:

    try {

        doable.doIt();  // Specified to throw several different exceptions

    } catch (Throwable ex) {

        logger.log(ex);

        throw ex;   // Won't compile unless method is specified to throw Throwable!

    }

Unfortunately, it is not generally possible to do this, as the resulting catch clause throws the type of exception that was caught, which the enclosing method is typically not specified to throw.  To get around this, programmers often wrap the exception prior to rethrowing it:

    try {  
        doable.doIt();

    } catch (Throwable ex) {

        logger.log(ex);

        throw new WrappedException(ex);  // Obscures exception type!

    }

If a caught exception is declared final, it is safe to rethrow any caught exception:

    try {

        doable.doIt();

    } catch (final   Throwable ex) {

        logger.log(ex);

        throw ex;

    }

Because the catch parameter is final, it can only hold exceptions that are thrown from the try block. Exception checking should take advantage of that fact: the compiler should treat this rethrown exception as if it can throw only checked exceptions that occur in the try block.

还有其他的希望大家补充!!

分享到:
评论

相关推荐

    JDK 7 新特性小结实例代码解析

    JDK 7 是Java开发的一个重要版本,引入了许多新的特性和改进,提升了开发效率和代码的可读性。以下是对这些新特性的详细说明: 1. **Switch 支持 String 做参数** 在JDK 7之前,switch语句只支持基本数据类型(如...

    JDK资源包合集(JDK6+JDK7+JDK8)

    此外,JDK7还引入了新的类型 inference(类型推断)特性,使得编写泛型代码更加简洁,同时提升了垃圾收集器的效率,进一步优化了程序性能。 JDK8,又名Java SE 8(标准版8),是2014年发布的,其最大的变化就是引入...

    jdk1.5 1.6 1.7的新特征总结

    【JDK1.5新特性】 1. 泛型(Generic) JDK1.5引入了泛型,这是对类型安全的重要改进。泛型允许在集合类中指定元素的类型,确保了在编译时就能进行类型检查,避免了运行时的强制类型转换和可能的ClassCastException...

    JDK5.0的11个主要新特征

    JDK5.0是Java开发的一个重要里程碑,它引入了11个主要的新特性,极大地提升了编程效率和代码安全性。以下是对这些特性的详细说明: 1. 泛型(Generic) 泛型的引入是为了解决类型安全问题,避免在运行时进行不必要...

    JDK8新特性

    以下将详细讲解JDK8的一些核心新特性: 1. **lambda表达式**:这是Java 8最显著的特征之一,它引入了函数式编程的概念。Lambda表达式允许开发者以更简洁的方式编写匿名函数,尤其是在处理集合时,如Stream API的...

    JDK-中文版本和英文版本.zip

    本压缩包提供了不同版本的JDK,包括JDK6中文版本、JDK7英文版本、JDK8中文版本和JDK9中文版本,全部聚焦于Java Standard Edition (JavaSE),这是一个用于桌面应用和服务器端开发的基础平台。 1. **JDK6**:这个版本...

    最新Java JDK 8安装版(MacOS 64位)

    6. **Lambda表达式**:这是JDK 8最显著的特征之一,它提供了一种简洁的方式来表示匿名函数,使得代码更加简洁、易读。 7. **Stream API**:这个新API为处理集合数据提供了便利,支持链式操作,可简化大量数据的处理...

    jdk1.8 32位 免费下载

    1. **Lambda表达式**:这是Java 8最显著的特征之一,它引入了一种新的语法结构,允许开发者以更简洁的方式处理函数式编程任务。Lambda表达式使得代码更加紧凑,提高了可读性,尤其在处理集合操作时非常有用。 2. **...

    最新Java JDK 8免安装版(Linux 64位)

    7. **新的类型接口**:比如`Optional`,用于表示可能为null的值,减少空指针异常的发生,提高代码的健壮性。 8. **新的反射API**:Java 8的反射API增加了对注解的支持,使得在运行时检查和操作注解变得更加简单。 ...

    jdk 1.7和1.8.zip

    这个压缩包“jdk 1.7和1.8.zip”提供了Java的两个主要版本:JDK 1.7(也称为Java 7)和JDK 1.8(也称为Java 8),这两个版本在Java发展历程中扮演了重要的角色。 **JDK 1.7(Java 7)** JDK 1.7是在2011年发布的,...

    jdk-7u2-linux-i586.rpm for 32位RedHat下载及安装配置步骤.txt

    该版本为32位操作系统RedHat的rpm安装包版本,要了解jdk的新版本特征或window版本及其他版本内容参考更多页

    jdk-8u231-linux-x64.tar.gz

    2. **Lambda表达式**:这是JDK8最显著的特征之一,它提供了函数式编程的能力,简化了处理集合的操作,例如流API(Stream API)的使用。 3. **流(Stream)**:Java 8的Stream API允许对集合进行声明式处理,可以方便...

    jdk-8u152-windows-i586

    7. **Java Mission Control** 和 **Java Flight Recorder**:这两个工具是Java 8引入的性能分析和监控工具,帮助开发者深入理解应用的性能特征和问题。 8. **Java控制面板**:提供图形用户界面,用于管理Java设置,...

    jdk-7u79-windows-x64

    【标签】"jdk 1.7 64位 官方下载" 进一步强调了该文件的核心特征:它是官方提供的,确保了软件的安全性和可靠性;是64位的,这意味着它能够利用64位系统的全部计算能力,处理更大的数据量;以及它属于JDK 1.7系列,...

    jdk1.5后的特性.rar

    - **类型推断**:JDK 7 引入了类型推断,简化了泛型的使用,使得开发者不必在每个地方都显式指定类型参数。 ### 2. 枚举(Enums) 枚举是 JDK 1.5 中引入的另一种新特性,用于替代传统的常量类,提供了一种更安全...

    jdk1.8中文文档.CHM

    4. **Lambda表达式**:JDK1.8引入的Lambda表达式是函数式编程的重要特征,它简化了对匿名函数的处理,使代码更加简洁易读。通过Lambda,可以更方便地处理集合和进行并行计算。 5. **Stream API**:Stream API是处理...

    jdk-8u111-windows-x64 (1)

    JDK 8是Oracle公司于2014年3月18日正式发布的,带来了许多重要的新特性和改进,对Java开发者来说意义重大。 **一、JDK 8的新特性** 1. **Lambda表达式**:这是Java 8最显著的特征之一,引入了函数式编程的概念。...

    jdk 8 10大特性 + json 转 excel.zip

    1. **lambda表达式**:Lambda表达式是JDK 8最显著的特征之一,它允许函数作为方法参数或变量存储,使得编写简洁的匿名函数成为可能。通过这种方式,可以更方便地处理集合和流API。 2. **函数式接口**:为了支持...

    配置Linux中jdk、mysql、tomcat

    首先,通过`rz`命令上传JDK的tar.gz文件,如`jdk-7u71-linux-x64.tar.gz`。解压文件至指定目录,如`/usr/src/jdk`。接着,配置环境变量,在`/etc/profile`中添加`JAVA_HOME`、`PATH`和`CLASS_PATH`。更新配置后,...

    jdk8.CHM中文版

    Lambda表达式是Java 8最显著的特征之一,它简化了函数式编程,使得编写简洁的代码成为可能。Lambda表达式可以替代那些具有单个抽象方法的接口实现,如Runnable、Comparator等。例如: ```java List&lt;String&gt; names...

Global site tag (gtag.js) - Google Analytics