/modules/extension/src/main/java/org/springside/modules/utils/UnsafeSupport.java

https://github.com/yangjiandong/sshapp · Java · 79 lines · 23 code · 8 blank · 48 comment · 0 complexity · 5e0731c230a0eade999e09c17a1706c5 MD5 · raw file

  1. package org.springside.modules.utils;
  2. /*
  3. * Copyright 2010, the original author or authors. All rights reserved.
  4. */
  5. import java.lang.reflect.Field;
  6. import org.apache.log4j.Logger;
  7. import sun.misc.Unsafe;
  8. /**
  9. * 获取{@link sun.misc.Unsafe}实例<br>
  10. * 从rt.jar包中反编译该类获取的信息
  11. *
  12. * <pre>
  13. *
  14. * package sun.misc;
  15. *
  16. * import java.lang.reflect.Field;
  17. * import java.lang.reflect.Modifier;
  18. * import java.security.ProtectionDomain;
  19. * import sun.reflect.Reflection;
  20. *
  21. * public final class Unsafe
  22. * {
  23. * private static final Unsafe theUnsafe;
  24. * public static final int INVALID_FIELD_OFFSET = -1;
  25. *
  26. * private static native void registerNatives();
  27. *
  28. * public static Unsafe getUnsafe()
  29. * {
  30. * Class localClass = Reflection.getCallerClass(2);
  31. * if (localClass.getClassLoader() != null)
  32. * throw new SecurityException(&quot;Unsafe&quot;);
  33. * return theUnsafe;
  34. * }
  35. * static
  36. * {
  37. * registerNatives();
  38. *
  39. * theUnsafe = new Unsafe();
  40. * }
  41. * ..........................
  42. * </pre>
  43. *
  44. * @author <a href="mailto:xiao_jiang51@163.com">xiao jiang</a>
  45. * @version %I%, %G%
  46. * @history 2010-12-23
  47. */
  48. public class UnsafeSupport {
  49. private static Logger log = Logger.getLogger(UnsafeSupport.class);
  50. private static Unsafe unsafe;
  51. static {
  52. Field field;
  53. try {
  54. // 由反编译Unsafe类获得的信息
  55. field = Unsafe.class.getDeclaredField("theUnsafe");
  56. field.setAccessible(true);
  57. // 获取静态属性,Unsafe在启动JVM时随rt.jar装载
  58. unsafe = (Unsafe) field.get(null);
  59. } catch (Exception e) {
  60. log.error("Get Unsafe instance occur error", e);
  61. }
  62. }
  63. /**
  64. * 获取{@link Unsafe }
  65. */
  66. public static Unsafe getInstance() {
  67. return unsafe;
  68. }
  69. public static void main(String[] args) {
  70. }
  71. }