/commons/src/main/java/org/infinispan/commons/jdkspecific/CallerId.java

https://github.com/wburns/infinispan · Java · 40 lines · 35 code · 5 blank · 0 comment · 8 complexity · b01151830be43b026ad26bb6df08075f MD5 · raw file

  1. package org.infinispan.commons.jdkspecific;
  2. import sun.reflect.Reflection;
  3. public class CallerId {
  4. private static final boolean hasGetCallerClass;
  5. private static final int callerOffset;
  6. private static final LocalSecurityManager SECURITY_MANAGER;
  7. static {
  8. boolean result = false;
  9. int offset = 1;
  10. try {
  11. result = Reflection.getCallerClass(1) == CallerId.class || Reflection.getCallerClass(2) == CallerId.class;
  12. offset = Reflection.getCallerClass(1) == Reflection.class ? 2 : 1;
  13. } catch (Throwable ignored) {
  14. }
  15. hasGetCallerClass = result;
  16. callerOffset = offset;
  17. if (!hasGetCallerClass) {
  18. SECURITY_MANAGER = new LocalSecurityManager();
  19. } else {
  20. SECURITY_MANAGER = null;
  21. }
  22. }
  23. private static class LocalSecurityManager extends SecurityManager {
  24. public Class<?>[] getClasses() {
  25. return this.getClassContext();
  26. }
  27. }
  28. public static Class<?> getCallerClass(int n) {
  29. if (hasGetCallerClass) {
  30. return Reflection.getCallerClass(n + callerOffset);
  31. } else {
  32. return SECURITY_MANAGER.getClasses()[n + callerOffset];
  33. }
  34. }
  35. }