正确使用arrayBaseOffset和arrayIndexScale

时间:2014-04-03 18:57:53

标签: java arrays unsafe

我已经定义了一个简单的数组,我希望将Unsafe.arrayBaseOffsetUnsafe.arrayIndexScale与以下代码段一起使用。

import sun.misc.Unsafe;
public class Arr
{
  public static void main(String[] args)
  {
    int [] a = new int[3];
    a[0] = 10; a[1] = 20; a[2] = 30;
    int baseOffset = Unsafe.arrayBaseOffset(a.getClass());
    int indexScale = Unsafe.arrayIndexScale(a.getClass());
  }
} 

但是我收到了这些错误

Arr.java:11: non-static method arrayBaseOffset(java.lang.Class) cannot be referenced from a static context
    int baseOffset = Unsafe.arrayBaseOffset(a.getClass());
                           ^

Arr.java:12: non-static method arrayIndexScale(java.lang.Class) cannot be referenced from a static context
    int indexScale = Unsafe.arrayIndexScale(a.getClass());
                           ^

1 个答案:

答案 0 :(得分:3)

arrayBaseOffsetarrayIndexScale方法不是静态的,因此您无法按照自己的方式调用它们。你需要这样做:

    Unsafe u = Unsafe.getUnsafe();
    int baseOffset = u.arrayBaseOffset(a.getClass());
    int indexScale = u.arrayIndexScale(a.getClass());