`
lirig
  • 浏览: 235462 次
  • 性别: 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.

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

分享到:
评论

相关推荐

    jdk1.5 1.6 1.7的新特征总结

    jdk1.5 1.6 1.7的新特征总结,面试经常会被问到的。

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

    通过实例代码给大家介绍了JDK 7 新特性小结篇,感兴趣的朋友一起看看吧

    jdk-7u79-windows-x64.rar

    Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征

    JDK5.0的11个主要新特征.doc

    1 泛型(Generic) ...7 元数据(Meta data) 8 Building Strings(StringBuilder类) 9 控制台输入(Console Input) 10 Covariant Return Types(不晓得怎么翻译,大概是 改变返回类型) 11 格式化I/O(Formatted I/O)

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

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

    java jdk实列宝典 光盘源代码

    12反射 是java程序开发的特征之一,允许java程序对自身进行检查,并能直接操作程序的内部属性; instanceof操作符,instanceof.java; 获取类的信息,ViewClassInfoJrame.java; 动态调用类的方法,CallMetod.java; ...

    Java SE 7 API文档

    jdk7 API文档。Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极...

    Spring hibernate SpringMVC整合对数据库操作

    由于spring3.x,基于asm的某些特征,而这些asm还没有用jdk8编译,所以采用Spring 3+JDK8就会报错,提示错误信息( java.lang.IllegalArgumentException),具体解决方案有:1、Spring 3+JDK7及以下版本 2、Spring 4+JDK8...

    slush-lib-java:用于 Java 库的 Slush 生成器

    jdk 兼容性检查(项目配置为 1.6 兼容性,而您可以使用任何 jdk 来构建) 代码质量检查(pmd、checkstyle、findbugs) 发布流程(如maven发布) 注意:checkstyle 6.2 需要 jdk7 或更高版本,因此如果您使用质量检查...

    java7hashmap源码-Java-:Java-

    相对于java7,Java8的新特性如下: 接口的默认方法;Java 8允许给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法。 Lambda 表达式;eg:接受2个参数(数字),并返回他们的差值...

    docker-aosp:用于检出AOSP分支并在源代码树中构建外部代码的Docker映像-docker source code

    码头工人 ... 支持JDK7(带有openstf / aosp:jdk7) 支持JDK8(带有openstf / aosp:jdk8) 在Docker Hub注册表中以提供。 要求 大量的磁盘空间。 当前,本地镜像大约需要60GB,在构建模块及其部

    第7章-大数据分析与挖掘技术---大数据基础.pptx

    Mahout安装与配置 6 (1)安装JDK+IDEA集成开发环境; (2)安装配置maven; (3)安装配置Mahout; (4)安装配置Hadoop伪分布式环境。 第7章-大数据分析与挖掘技术---大数据基础全文共37页,当前为第6页。 Mahout...

    Java复习大纲面试题.doc

    7.面向对象的三大特征是什么? 封装、继承、多态 8.Java实现多态性的机制是什么? 有继承 有方法重写 父类引用指向子类对象 9.什么是方法重载?什么是方法重写?方法重载与方法重写的区别? 方法重载(Overload):是指...

    JavaSE基础面试题.docx

    20.jdk7/8中对HashMap做了哪些改变? 21.负载因子为什么会影响HashMap性能 22.为什么HashMap中initailCapacity要设置成2的n次幂 23.ConcurrentHashMap分段式加锁是如何实现 24.HashMap存储null值的底层实现 25.叙述...

    开源版值联云卡自动售卡商业系统v2.0.0+图文搭建教程

    1. Linux 引荐 centos7 以上版本 2. 宝塔环境: 引荐最新版本 3. Mysql版本:5.7 4. Jdk版本:1.8 适用场景: 适用于各种电商、优惠卷、论坛约请码、充值卡、激活码、注册码、腾讯爱奇艺积分CDK等,支持手动和全...

    面试必问Java面试题,对标初级Java

    1.Java泛型(约束类型) 2.Java中函数式编程-Stream流-Lambda表达式 3.JVM虚拟机 4.Springcloud里面的组件 5.说一下你对分布式理解是什么样的? 6.多线程 7. java集合 ...20.Java面向对象有哪些特征

    java认证所有课程

    - 新的事件模型提供对JavaBeans的支持。 这种方法也有一个缺点: - 尽管当前的JDK支持委托模型和JDK1.0事件模型,但不能混合使用JDK1.0和JDK1.1。 第五节 图形用户界面的行为 9.5.1 事件类型 我们已经介绍了在单一...

    SEPR-Project-JKG:这个存储库保存了 Off the Rails 的文件,这是 JKG 团队的第二年 SEPR 项目

    要编辑和运行源代码,需要 libGDX 和 JDK 7(及更高版本)。 推荐使用 Eclipse,但不是必需的。 框架特性 当前的源代码允许简单的可扩展性和简单的扩展以及要添加到游戏中的额外功能。 由于 Java 的面向对象的特性...

    Generator:用于生成高效等号、哈希码等的通用生成器插件

    特征它使用 jdk 7 Objects 类来生成高效紧凑的代码。 它减少了大量的代码行。 不存在圈复杂度问题。如何安装? 从 dist 文件夹下载插件 jar 将其放在 dropins 文件夹下重新启动Eclipse。 瞧,插件应该安装成功如何...

    google-rfc-2445:从 https 克隆

    #Google RFC 2445 这是上 google-rfc-2455 项目的 mavenized 版本。 ##目的 RFC 2445 描述了日历互操作性的方案。 该项目实现了 RFC 2445 的核心部分,包括重复规则... Java JDK 7 或更高版本 要构建罐子: git

Global site tag (gtag.js) - Google Analytics