Assertion in Java

本文深入探讨了Java中的断言机制,包括其形成、使用场景、如何在代码中加入断言以及如何启用和禁用断言。通过实例演示,帮助开发者在编程过程中有效利用断言进行错误检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   An assertion is a statement in the Java language that enables us to test our assumptions about our program. For example, if we write a method to calculate the money in our pocket, then we might assert that the total value is more than 0.
 

1. Assert forms.

       1) assert Expression1;
       Where the Expression1is a Boolean expression. When the system run the assert, it evaluate Expression, and if it is false,  it would throw AssertionError with no detail message. Pls noted that AssertionError inherit from Error
 
       2) assert Expression1Expression2;
where: 
  •  Expression1 is a boolean expression.
  • Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)
 
Pls noted that AssertionError inherit from Error, so we may hv no need to handle, also may catch it as normal Error.
 

2. Putting assert into Code.

1) Internal Invariants
  You should now use an assertion whenever you would have written a comment that asserts an invariant.
if (i % 3 == 0) {
        ...
    } else if (i % 3 == 1) {
        ...
    } else {
        assert i % 3 == 2 : i;
        ...
    }
 
2) Control-Flow Invariants
  It points out another general area where you should use assertions: place       an assertion at any location you assume will not be reached.
 
void foo() {
        for (...) {
            if (...)
                return;
        }
        assert false; // Execution should never reach this point!
    }
 
3) Preconditions.
 
private void setDelegationInfoIntoSubmissionDto(…) {
 assert  isf10Snapshot.getIsfDelegation()!=null;     
String delegatorCompanyId = isf10Snapshot.getIsfDelegation().getDelegatorCompanyID();
        submissionDTO.setDelegator(true);
        … 
               }
 

3. Enabling/Disabling Assertions.

1) To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch. You specify the granularity with the arguments that you provide to the switch:
· no arguments 
   Enables or disables assertions in all classes except system classes.
· packageName... 
   Enables or disables assertions in the named package and any subpackages.
· ...
   Enables or disables assertions in the unnamed package in the current working directory.
·className
   Enables or disables assertions in the named class
2) Enable it in oc4j
      Use -esa | -enablesystemassertions to enable system assertions;
      Use -dsa | -disablesystemassertions to disable system assertions
 
3) Enable it in Eclipse
   In run configuration dialog, switch to Arguments tab, input –ea/-da in VM arguments filed.
  

4.Performance

       The Assertion mechanism is as following. When the compiler finds an assertion in a class, it adds a generated static final field named $assertionDiabled to the class. And the assertion itself is compiled into a statement of the form:
      if($assertionDisabled)
           if(!boolean_expression)
                      throw new assertionError(String_Expression);
 
so, if assertion overhead, it would introduce an performance issue into system, no matter the assertion is enabled or disabled.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值