张凯1 2021-03-29 17:35 采纳率: 50%
浏览 98

Unsafe类的问题,arrayIndexScale注释看不懂

/**
 * Report the scale factor for addressing elements in the storage
 * allocation of a given array class.  However, arrays of "narrow" types
 * will generally not work properly with accessors like {@link
 * #getByte(Object, int)}, so the scale factor for such classes is reported
 * as zero.
 *
 * @see #arrayBaseOffset
 * @see #getInt(Object, long)
 * @see #putInt(Object, long, int)
 */
public native int arrayIndexScale(Class<?> arrayClass);
* However, arrays of "narrow" types
* will generally not work properly with accessors like {@link
* #getByte(Object, int)}, so the scale factor for such classes is reported
* as zero.

这块注释啥意思呢?我看不懂,有大神可以举例解答一下吗?

  • 写回答

1条回答 默认 最新

  • hi wei 新星创作者: Java技术领域 2023-02-21 10:42
    关注

    arrayIndexScale获取的是数组对象中元素存储的偏移量。看下面示例,就明白了:

    private void arrayTest() {
        String[] array=new String[]{"str1str1str","str2","str3"};
        int baseOffset = unsafe.arrayBaseOffset(String[].class);
        System.out.println(baseOffset);
        int scale = unsafe.arrayIndexScale(String[].class);
        System.out.println(scale);
     
        for (int i = 0; i < array.length; i++) {
            int offset=baseOffset+scale*i;
            System.out.println(offset+" : "+unsafe.getObject(array,offset));
        }
    }
    

    结果:

    img

    评论

报告相同问题?