服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

jdk1.4新特性:断言

  摘要

????jdk1.4中引入的一个新特性之一就是断言(assert),为程序的调试提供了强有力的支持,以下的文档根据suntec内容及相关内容组成。

  源代码:

/**
* simple examples of the use of the new assertion feature in jdk1.4
*
* @author s.ritter 16/7/2001
**/

public class assertexample {

  public static void main(string[] args) {
    int x = 10;
    if (args.length > 0) {
      try {
        x = integer.parseint(args[0]);
      } catch (numberformatexception nfe) {
        /* ignore */
      }
    }
    system.out.println("testing assertion that x == 10");
    assert x == 10:"our assertion failed";
    system.out.println("test passed");
  }

}

  由于引入了一个新的关键字,所以在编译的时候就需要增加额外的参数,要编译成功,必须使用jdk1.4的javac并加上参数'-source 1.4',例如可以使用以下的命令编译上面的代码:

????javac -source 1.4 assertexample.java

  以上程序运行使用断言功能也需要使用额外的参数(并且需要一个数字的命令行参数),例如:

????java -ea assertexample 1

  程序的输出为:

????testing assertion that x == 10
????exception in thread "main" java.lang.assertionerror:
????our assertion failed
????at assertexample.main(assertexample.java:20)

  由于输入的参数不等于10,因此断言功能使得程序运行时抛出断言错误,注意是错误,这意味着程序发生严重错误并且将强制退出。断言使用boolean值,如果其值不为true则抛出assertionerror并终止程序的运行。

?? 由于程序员的问题,断言的使用可能会带来副作用,例如:

????boolean isenable=false;
????//...
????assert isenable=true;

  这个断言的副作用是因为它修改程序变量的值并且没有抛出错误,这样的错误如果不细心检查很难发现。但是同时我们可以根据以上的副作用得到一个有用的特性,根据它测试是否将断言打开了。

/**
* simple examples test enable assertion feature in jdk1.4
*
* @author cherami 25/4/2002
**/

public class assertexample2 {

  public static void main(string[] args) {
    boolean assertenable=false;
    assert assertenable=true;
    if (assertenable==false){
      throw new runtimeexception("assertions should be enable");
    }
  }

}

  如果我们不使用-ea参数运行上面的程序,则控制台将输出:

????exception in thread "main" java.lang.runtimeexception:
????assertions should be enab
????le
????at assertexample.main(assertexample.java:14)

扫描关注微信公众号