Java assert 关键字使用
2017-10-18 00:00
357 查看
关于Java assert关键字的使用,参考Stack Overflow的高票回答:
What are some real life examples to understand the key role of assertions?
这段话的翻译是:
Java 1.4 加入了断言(也就是assert关键字)。 它们被用来检验代码中的不变条件的正确性。 它们不应该在生产环境中被触发,而应该用来指示BUG或者代码路径的误用。可以通过在Java命令行加上-ea 选项来在运行时启用它们,但是默认情况下,它们是关闭的。
一说,根据Oracle的官方文档,assert不应该用来检验public方法的参数,而应该用抛异常来代替。
请注意,这里说的是不是像网上的文章说的不使用assert关键字,规范的使用断言可以增加代码可读性,但是在生产环境中不应该触发任何的assert条件。
参考文献: http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html
What are some real life examples to understand the key role of assertions?
Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -eaoption on the javacommand, but are not turned on by default. An example: public Foo acquireFoo(int id) { Foo result = null; if (id > 50) { result = fooService.read(id); } else { result = new Foo(id); } assert result != null; return result; } |
Java 1.4 加入了断言(也就是assert关键字)。 它们被用来检验代码中的不变条件的正确性。 它们不应该在生产环境中被触发,而应该用来指示BUG或者代码路径的误用。可以通过在Java命令行加上-ea 选项来在运行时启用它们,但是默认情况下,它们是关闭的。
一说,根据Oracle的官方文档,assert不应该用来检验public方法的参数,而应该用抛异常来代替。
请注意,这里说的是不是像网上的文章说的不使用assert关键字,规范的使用断言可以增加代码可读性,但是在生产环境中不应该触发任何的assert条件。
参考文献: http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html
相关文章推荐
- Java关键字final、static使用总结
- Java关键字final、static使用总结
- Java关键字final、static使用总结
- Java关键字final、static,抽象类,接口使用总结
- Java关键字final、static 抽象类 接口使用总结
- Java关键字final、static使用总结
- this关键字的使用(摘录Thinking In Java)
- Java关键字final、static使用
- Java关键字final、static使用总结
- Java关键字final、static使用总结
- Java关键字this、super使用总结
- Java关键字final、static使用总结
- Java关键字final、static使用总结
- Java关键字final、static使用总结
- Java陷阱之assert关键字
- Java关键字final、static使用总结
- Java关键字this、super使用总结
- Java关键字final、static使用总结
- NC与防御式编程及Java关键字assert
- Java中的break和continue关键字使用总结