lundi 19 mai 2014

Java - utilisation correcte des arrayBaseOffset et arrayIndexScale - Stack Overflow


I have defined a simple array and I want to use Unsafe.arrayBaseOffset and Unsafe.arrayIndexScale with the following snippet.


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());
}
}

However I get these errors


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());
^



The arrayBaseOffset and arrayIndexScale methods are not static, so you cannot call them the way you are. You need to do it like this:


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


I have defined a simple array and I want to use Unsafe.arrayBaseOffset and Unsafe.arrayIndexScale with the following snippet.


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());
}
}

However I get these errors


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());
^


The arrayBaseOffset and arrayIndexScale methods are not static, so you cannot call them the way you are. You need to do it like this:


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

0 commentaires:

Enregistrer un commentaire