为什么在Integer类的Integer.valueOf方法中使用assert? [英] Why is assert used in the Integer.valueOf method of the Integer class?

查看:487
本文介绍了为什么在Integer类的Integer.valueOf方法中使用assert?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在深入研究 Integer 类实际上如何使用缓存对象,我在 Integer.valueOf 方法:

  public static Integer valueOf(int i){
assert IntegerCache.high> = 127 ;
if(i> = IntegerCache.low&& i< = IntegerCache.high)
返回IntegerCache.cache [i +( - IntegerCache.low)];
返回新的整数(i);
}

我的问题是:




解决方案

断言的目的是建立不变量并记录实施。在这里,这个断言记录了当输入 valueOf 方法时 IntegerCache.high 值保证至少为127.最好编写一个assert而不是注释,因为当相应的命令行选项( -esa )处于活动状态时,JVM也会检查断言。 / p>

通常这个断言永远不会抛出,因为 IntegerCache.high 以这种方式初始化:

  int h = 127; 
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty(java.lang.Integer.IntegerCache.high);
if(integerCacheHighPropValue!= null){
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i,127);
//最大数组大小为Integer.MAX_VALUE
h = Math.min(i,Integer.MAX_VALUE - ( - low)-1);
} catch(NumberFormatException nfe){
//如果无法将属性解析为int,请忽略它。
}
}
high = h;

此代码保证该值至少为127.因此,如果修改<,则断言可以抛出 IntegerCache.high (使用反射和 setAccessible(true))或者如果将来修改JDK并且bug将会在 IntegerCache.high 初始化代码中引入。这就是断言存在的原因:捕捉错误。


I was digging into how the Integer class actually uses cached objects, and I found the below code in the Integer.valueOf method:

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

My question is:

解决方案

The purpose of asserts is to establish invariants and to document the implementation. Here, this assert documents the fact that when the valueOf method is entered IntegerCache.high value is guaranteed to be at least 127. It's better to write an assert instead of the comment, because the assert will also be checked by the JVM when the corresponding command line option (-esa) is active.

Normally this assert will never throw, because the IntegerCache.high is initialized in this way:

int h = 127;
String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
    try {
        int i = parseInt(integerCacheHighPropValue);
        i = Math.max(i, 127);
        // Maximum array size is Integer.MAX_VALUE
        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
    } catch( NumberFormatException nfe) {
        // If the property cannot be parsed into an int, ignore it.
    }
}
high = h;

This code guarantees that the value will be at least 127. So the assert can throw if you modify IntegerCache.high (using reflection and setAccessible(true)) or if the JDK will be modified in the future and bug will be introduced in IntegerCache.high initialization code. That's why asserts exist: to catch bugs.

这篇关于为什么在Integer类的Integer.valueOf方法中使用assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆