How do I find the caller of a method using stacktrace or reflection?

后端 未结 12 1461
鱼传尺愫
鱼传尺愫 2020-11-21 13:26

I need to find the caller of a method. Is it possible using stacktrace or reflection?

12条回答
  •  误落风尘
    2020-11-21 13:57

    Here is a part of the code that I made based in the hints showed in this topic. Hope it helps.

    (Feel free to make any suggestions to improve this code, please tell me)

    The counter:

    public class InstanceCount{
        private static Map instanceMap = new HashMap();
    private CounterInstanceLog counterInstanceLog;
    
    
        public void count() {
            counterInstanceLog= new counterInstanceLog();
        if(counterInstanceLog.getIdHashCode() != 0){
        try {
            if (instanceMap .containsKey(counterInstanceLog.getIdHashCode())) {
             counterInstanceLog= instanceMap .get(counterInstanceLog.getIdHashCode());
        }
    
        counterInstanceLog.incrementCounter();
    
                instanceMap .put(counterInstanceLog.getIdHashCode(), counterInstanceLog);
        }
    
        (...)
    }
    

    And the object:

    public class CounterInstanceLog{
        private int idHashCode;
        private StackTraceElement[] arrayStackTraceElements;
        private int instanceCount;
        private String callerClassName;
    
        private StackTraceElement getProjectClasses(int depth) {
          if(depth< 10){
            getCallerClassName(sun.reflect.Reflection.getCallerClass(depth).getName());
            if(getCallerClassName().startsWith("com.yourproject.model")){
                setStackTraceElements(Thread.currentThread().getStackTrace());
                setIdHashCode();
            return arrayStackTraceElements[depth];
            }
            //+2 because one new item are added to the stackflow
            return getProjectClasses(profundidade+2);           
          }else{
            return null;
          }
        }
    
        private void setIdHashCode() {
            if(getNomeClasse() != null){
                this.idHashCode = (getCallerClassName()).hashCode();
            }
        }
    
        public void incrementaContador() {
        this.instanceCount++;
    }
    
        //getters and setters
    
        (...)
    
    
    
    }
    

提交回复
热议问题