我已经定义了一个简单的数组,我希望将Unsafe.arrayBaseOffset
和Unsafe.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());
^
答案 0 :(得分:3)
arrayBaseOffset
和arrayIndexScale
方法不是静态的,因此您无法按照自己的方式调用它们。你需要这样做:
Unsafe u = Unsafe.getUnsafe();
int baseOffset = u.arrayBaseOffset(a.getClass());
int indexScale = u.arrayIndexScale(a.getClass());