使用Unsafe时未报告的异常

时间:2014-04-04 11:07:11

标签: java exception unsafe

我写了一个简单的代码,在数组上使用Unsafe.prefetchRead并使用this测试代码作为模板。

import sun.misc.Unsafe;
import java.lang.reflect.*;
public class Arr {
  static int [] a = new int[3];
  static Unsafe unsafe;
  static int baseOffset, indexScale;
  public static void main(String[] args)  {
    a[0] = 10;    a[1] = 20;    a[2] = 30;

    Class c = Arr.class.getClassLoader().loadClass("sun.misc.Unsafe");
    Field f = c.getDeclaredField("theUnsafe");
    f.setAccessible(true);
    unsafe = (Unsafe)f.get(c);

    baseOffset = unsafe.arrayBaseOffset(int[].class);
    indexScale = unsafe.arrayIndexScale(int[].class);
    for (int i = 0; i < 3; i++)  {
      unsafe.prefetchReadStatic(a, baseOffset+indexScale*i);
      System.out.println(a[i]);
    }
  }
}

但是我收到了这些错误

Arr.java:14: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
    Class c = Arr.class.getClassLoader().loadClass("sun.misc.Unsafe");
                                                  ^
Arr.java:15: unreported exception java.lang.NoSuchFieldException; must be caught or declared to be thrown
    Field f = c.getDeclaredField("theUnsafe");
                                ^
Arr.java:17: unreported exception java.lang.IllegalAccessException; must be caught or declared to be thrown
    unsafe = (Unsafe)f.get(c);
                          ^

1 个答案:

答案 0 :(得分:3)

要使其正常运行,请将public static void main(String[] args) {更改为public static void main(String[] args) throws Exception {

然后read up on exceptionsClassLoader#loadClass(String)方法抛出声明的异常ClassNotFoundException。您必须处理它,或允许它被抛出您的方法。其他两个错误相同。