/src/CornerCube/Lang/CallStackUtils.java

https://github.com/gencube/CornerCube · Java · 60 lines · 41 code · 8 blank · 11 comment · 3 complexity · 6dc85d1785664edc07126dd9f8a26f8d MD5 · raw file

  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package CornerCube.Lang;
  6. /**
  7. * Use this simple info to do debugging.
  8. * @author MatthewOng
  9. */
  10. public class CallStackUtils {
  11. public static CallerInfo getCallerInfo() {
  12. return getCallerInfo(0);
  13. }
  14. public static CallerInfo getCallerInfo(int level) {
  15. Class caller = cism.getCallerClass(level + 1);
  16. //Class caller =sun.reflect.Reflection.getCallerClass(level+1);
  17. String clsName = caller.getSimpleName();
  18. String pkgName = caller.getCanonicalName().replaceFirst("." + clsName, "");
  19. CallerInfo info = CallerInfo.getNewIntance(pkgName, clsName, null, null, null);
  20. // info is not debug, there will not be any method & source file name.
  21. return info;
  22. }
  23. private static final CallerInfoSecurityManager cism = new CallerInfoSecurityManager();
  24. private static class CallerInfoSecurityManager extends SecurityManager {
  25. public Class getCallerClass(int level) {
  26. Class caller = getClassContext()[level];
  27. return caller;
  28. }
  29. }
  30. public static CallerInfo getCallerDebug() {
  31. return getCallerDebug(1); // current level of caller
  32. }
  33. public static CallerInfo getCallerInfo(Throwable throwable) {
  34. if (throwable == null) {
  35. return getCallerDebug(1);
  36. } else {
  37. final StackTraceElement[] stes = throwable.getStackTrace();
  38. StackTraceElement ste = stes[stes.length - 1];
  39. return CallerInfo.getNewInstance(ste);
  40. }
  41. }
  42. public static CallerInfo getCallerDebug(int level) {
  43. try {
  44. final StackTraceElement[] stes = new Throwable().getStackTrace();
  45. StackTraceElement ste = stes[stes.length - level];
  46. return CallerInfo.getNewInstance(ste);
  47. } catch (Throwable e) {
  48. return null;
  49. //return "ERROR in getCaller"; // rather impossible to reach here.
  50. }
  51. }
  52. }