스택 추적이나 리플렉션을 사용하여 메서드 호출자를 어떻게 찾나요?

StackOverflow https://stackoverflow.com/questions/421280

  •  05-07-2019
  •  | 
  •  

문제

메서드 호출자를 찾아야 합니다.스택 추적이나 리플렉션을 사용하여 가능합니까?

도움이 되었습니까?

해결책

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

Javadocs에 따르면 :

배열의 마지막 요소는 스택의 바닥을 나타내며, 이는 시퀀스에서 가장 최근의 메소드 호출입니다.

StackTraceElement 가지다 getClassName(), getFileName(), getLineNumber() 그리고 getMethodName().

원하는 색인을 결정하려면 실험해야합니다 (아마도 stackTraceElements[1] 또는 [2]).

다른 팁

대체 솔루션은 이 강화 요청. 사용합니다 getClassContext() 관습 방법 SecurityManager 스택 추적 방법보다 빠른 것 같습니다.

다음 프로그램은 다른 제안 된 방법의 속도를 테스트합니다 (가장 흥미로운 비트는 내부 클래스에 있습니다. SecurityManagerMethod):

/**
 * Test the speed of various methods for getting the caller class name
 */
public class TestGetCallerClassName {

  /**
   * Abstract class for testing different methods of getting the caller class name
   */
  private static abstract class GetCallerClassNameMethod {
      public abstract String getCallerClassName(int callStackDepth);
      public abstract String getMethodName();
  }

  /**
   * Uses the internal Reflection class
   */
  private static class ReflectionMethod extends GetCallerClassNameMethod {
      public String getCallerClassName(int callStackDepth) {
          return sun.reflect.Reflection.getCallerClass(callStackDepth).getName();
      }

      public String getMethodName() {
          return "Reflection";
      }
  }

  /**
   * Get a stack trace from the current thread
   */
  private static class ThreadStackTraceMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return Thread.currentThread().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Current Thread StackTrace";
      }
  }

  /**
   * Get a stack trace from a new Throwable
   */
  private static class ThrowableStackTraceMethod extends GetCallerClassNameMethod {

      public String getCallerClassName(int callStackDepth) {
          return new Throwable().getStackTrace()[callStackDepth].getClassName();
      }

      public String getMethodName() {
          return "Throwable StackTrace";
      }
  }

  /**
   * Use the SecurityManager.getClassContext()
   */
  private static class SecurityManagerMethod extends GetCallerClassNameMethod {
      public String  getCallerClassName(int callStackDepth) {
          return mySecurityManager.getCallerClassName(callStackDepth);
      }

      public String getMethodName() {
          return "SecurityManager";
      }

      /** 
       * A custom security manager that exposes the getClassContext() information
       */
      static class MySecurityManager extends SecurityManager {
          public String getCallerClassName(int callStackDepth) {
              return getClassContext()[callStackDepth].getName();
          }
      }

      private final static MySecurityManager mySecurityManager =
          new MySecurityManager();
  }

  /**
   * Test all four methods
   */
  public static void main(String[] args) {
      testMethod(new ReflectionMethod());
      testMethod(new ThreadStackTraceMethod());
      testMethod(new ThrowableStackTraceMethod());
      testMethod(new SecurityManagerMethod());
  }

  private static void testMethod(GetCallerClassNameMethod method) {
      long startTime = System.nanoTime();
      String className = null;
      for (int i = 0; i < 1000000; i++) {
          className = method.getCallerClassName(2);
      }
      printElapsedTime(method.getMethodName(), startTime);
  }

  private static void printElapsedTime(String title, long startTime) {
      System.out.println(title + ": " + ((double)(System.nanoTime() - startTime))/1000000 + " ms.");
  }
}

2.4GHz Intel Core 2 Duo MacBook의 출력 예제 Java 1.6.0_17 :

Reflection: 10.195 ms.
Current Thread StackTrace: 5886.964 ms.
Throwable StackTrace: 4700.073 ms.
SecurityManager: 1046.804 ms.

내부 반사 방법은 다음과 같습니다 많이 다른 것보다 빠릅니다. 새로 생성 된 것으로 스택 추적을 얻습니다 Throwable 전류에서 얻는 것보다 빠릅니다 Thread. 그리고 발신자 클래스를 찾는 비 내부 방법 중에서 SecurityManager 가장 빠른 것 같습니다.

업데이트

처럼 Lyomi 지적합니다 이 의견 그만큼 sun.reflect.Reflection.getCallerClass() Java 7 업데이트 40에서 기본적으로 메소드가 비활성화되었고 Java 8에서 완전히 제거되었습니다. 자세히 알아보십시오. Java 버그 데이터베이스 에서이 문제.

업데이트 2

처럼 Zammbi 오라클이 발견되었습니다 변화에서 철수해야합니다 그것은 그것을 제거했다 sun.reflect.Reflection.getCallerClass(). 여전히 Java 8에서 사용할 수 있습니다 (그러나 더 이상 사용되지 않음).

업데이트 3

3 년 후 : 현재 JVM으로 타이밍 업데이트.

> java -version
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
> java TestGetCallerClassName
Reflection: 0.194s.
Current Thread StackTrace: 3.887s.
Throwable StackTrace: 3.173s.
SecurityManager: 0.565s.

참조를 전달하지 않으려 고하는 것 같습니다. this 방법으로. 통과 this 현재 스택 추적을 통해 발신자를 찾는 것보다 훨씬 낫습니다. 더 oo 디자인으로 리팩토링하는 것이 더 좋습니다. 발신자를 알 필요는 없습니다. 필요한 경우 콜백 개체를 전달하십시오.

자바 9 - JEP 259:스택워킹 API

JEP 259 스택 추적의 정보를 쉽게 필터링하고 지연 액세스할 수 있는 효율적인 스택 탐색용 표준 API를 제공합니다.Stack-Walking API 이전에는 스택 프레임에 액세스하는 일반적인 방법은 다음과 같습니다.

Throwable::getStackTrace 그리고 Thread::getStackTrace 배열을 반환 StackTraceElement 각 스택 트레이스 요소의 클래스 이름과 메소드 이름을 포함하는 개체.

SecurityManager::getClassContext 보호된 방법입니다. SecurityManager 클래스 컨텍스트에 액세스하기 위한 서브클래스입니다.

JDK 내부 sun.reflect.Reflection::getCallerClass 어쨌든 사용해서는 안되는 방법

이러한 API를 사용하는 것은 일반적으로 비효율적입니다.

이 API는 VM이 ​​전체 스택의 스냅 샷을 간절히 캡처해야합니다., 전체 스택을 나타내는 정보를 반환합니다.발신자가 스택의 상위 몇 개의 프레임에만 관심이있는 경우 모든 프레임을 검사하는 비용을 피하는 방법은 없습니다.

즉시 발신자의 클래스를 찾으려면 먼저 StackWalker:

StackWalker walker = StackWalker
                           .getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

그런 다음 getCallerClass():

Class<?> callerClass = walker.getCallerClass();

또는 walk 그만큼 StackFrames 그리고 첫 번째 선행 항목을 얻습니다. StackFrame:

walker.walk(frames -> frames
      .map(StackWalker.StackFrame::getDeclaringClass)
      .skip(1)
      .findFirst());

짧막 한 농담:

Thread.currentThread().getStackTrace()[2].getMethodName()

2를 1로 교체해야 할 수도 있습니다.

이 방법은 똑같은 일을하지만 조금 더 간단하고 조금 더 성능을 발휘하며 반사를 사용하는 경우 해당 프레임을 자동으로 건너 뜁니다. 유일한 문제는 Jrockit 1.4-> 1.6의 런타임 클래스에 포함되어 있지만 Sun JVMS에 존재하지 않을 수 있습니다. (요점은 아닙니다 공공의 수업).

sun.reflect.Reflection

    /** Returns the class of the method <code>realFramesToSkip</code>
        frames up the stack (zero-based), ignoring frames associated
        with java.lang.reflect.Method.invoke() and its implementation.
        The first frame is that associated with this method, so
        <code>getCallerClass(0)</code> returns the Class object for
        sun.reflect.Reflection. Frames associated with
        java.lang.reflect.Method.invoke() and its implementation are
        completely ignored and do not count toward the number of "real"
        frames skipped. */
    public static native Class getCallerClass(int realFramesToSkip);

무엇까지 realFramesToSkip 값은 Sun 1.5 및 1.6 VM 버전이어야합니다. java.lang.System, getCallerClass ()라는 패키지 보호 방법이 있습니다. sun.reflect.Reflection.getCallerClass(3), 그러나 내 헬퍼 유틸리티 클래스에서 나는 도우미 클래스 호출의 추가 프레임이 있기 때문에 4를 사용했습니다.

     /**
       * Get the method name for a depth in call stack. <br />
       * Utility function
       * @param depth depth in the call stack (0 means current method, 1 means call method, ...)
       * @return method name
       */
      public static String getMethodName(final int depth)
      {
        final StackTraceElement[] ste = new Throwable().getStackTrace();

        //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
        return ste[ste.length - depth].getMethodName();
      }

예를 들어, 디버그 목적으로 호출 메소드 라인을 얻으려면 정적 메소드를 코딩하는 유틸리티 클래스를 지나야합니다.
(Old Java1.4 Code, 잠재적 인 스택 트레이시 레멘트 사용량을 설명하기 위해)

        /**
          * Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils". <br />
          * From the Stack Trace.
          * @return "[class#method(line)]: " (never empty, first class past StackTraceUtils)
          */
        public static String getClassMethodLine()
        {
            return getClassMethodLine(null);
        }

        /**
          * Returns the first "[class#method(line)]: " of the first class not equal to "StackTraceUtils" and aclass. <br />
          * Allows to get past a certain class.
          * @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils. 
          * @return "[class#method(line)]: " (never empty, because if aclass is not found, returns first class past StackTraceUtils)
          */
        public static String getClassMethodLine(final Class aclass)
        {
            final StackTraceElement st = getCallingStackTraceElement(aclass);
            final String amsg = "[" + st.getClassName() + "#" + st.getMethodName() + "(" + st.getLineNumber()
            +")] <" + Thread.currentThread().getName() + ">: ";
            return amsg;
        }

     /**
       * Returns the first stack trace element of the first class not equal to "StackTraceUtils" or "LogUtils" and aClass. <br />
       * Stored in array of the callstack. <br />
       * Allows to get past a certain class.
       * @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils. 
       * @return stackTraceElement (never null, because if aClass is not found, returns first class past StackTraceUtils)
       * @throws AssertionFailedException if resulting statckTrace is null (RuntimeException)
       */
      public static StackTraceElement getCallingStackTraceElement(final Class aclass)
      {
        final Throwable           t         = new Throwable();
        final StackTraceElement[] ste       = t.getStackTrace();
        int index = 1;
        final int limit = ste.length;
        StackTraceElement   st        = ste[index];
        String              className = st.getClassName();
        boolean aclassfound = false;
        if(aclass == null)
        {
            aclassfound = true;
        }
        StackTraceElement   resst = null;
        while(index < limit)
        {
            if(shouldExamine(className, aclass) == true)
            {
                if(resst == null)
                {
                    resst = st;
                }
                if(aclassfound == true)
                {
                    final StackTraceElement ast = onClassfound(aclass, className, st);
                    if(ast != null)
                    {
                        resst = ast;
                        break;
                    }
                }
                else
                {
                    if(aclass != null && aclass.getName().equals(className) == true)
                    {
                        aclassfound = true;
                    }
                }
            }
            index = index + 1;
            st        = ste[index];
            className = st.getClassName();
        }
        if(resst == null) 
        {
            //Assert.isNotNull(resst, "stack trace should null"); //NO OTHERWISE circular dependencies 
            throw new AssertionFailedException(StackTraceUtils.getClassMethodLine() + " null argument:" + "stack trace should null"); //$NON-NLS-1$
        }
        return resst;
      }

      static private boolean shouldExamine(String className, Class aclass)
      {
          final boolean res = StackTraceUtils.class.getName().equals(className) == false && (className.endsWith("LogUtils"
            ) == false || (aclass !=null && aclass.getName().endsWith("LogUtils")));
          return res;
      }

      static private StackTraceElement onClassfound(Class aclass, String className, StackTraceElement st)
      {
          StackTraceElement   resst = null;
          if(aclass != null && aclass.getName().equals(className) == false)
          {
              resst = st;
          }
          if(aclass == null)
          {
              resst = st;
          }
          return resst;
      }

나는 전에 이것을 해냈다. 새로운 예외를 만들고 스택 추적을 던지지 않고 스택 추적을 잡은 다음 스택 추적을 검사 할 수 있습니다. 다른 대답에서 알 수 있듯이, 그것은 매우 비싸다.

성능이 중요하지 않은 앱에서 로깅 유틸리티를 위해 이전에 해냈습니다 (실제로는 버튼 클릭과 같은 작업에 결과를 빠르게 표시하는 한 실제로는 거의 중요하지 않습니다).

스택 추적을 얻기 전에 예외는 .printstacktrace ()를 가졌으므로 System.out를 내 자신의 생성 스트림으로 리디렉션해야했습니다. System.out Back을 리디렉션하고 스트림을 구문 분석합니다. 재미있는 것들.

private void parseExceptionContents(
      final Exception exception,
      final OutputStream out)
   {
      final StackTraceElement[] stackTrace = exception.getStackTrace();
      int index = 0;
      for (StackTraceElement element : stackTrace)
      {
         final String exceptionMsg =
              "Exception thrown from " + element.getMethodName()
            + " in class " + element.getClassName() + " [on line number "
            + element.getLineNumber() + " of file " + element.getFileName() + "]";
         try
         {
            out.write((headerLine + newLine).getBytes());
            out.write((headerTitlePortion + index++ + newLine).getBytes() );
            out.write((headerLine + newLine).getBytes());
            out.write((exceptionMsg + newLine + newLine).getBytes());
            out.write(
               ("Exception.toString: " + element.toString() + newLine).getBytes());
         }
         catch (IOException ioEx)
         {
            System.err.println(
                 "IOException encountered while trying to write "
               + "StackTraceElement data to provided OutputStream.\n"
               + ioEx.getMessage() );
         }
      }
   }

다음은이 주제에서 보여준 힌트를 기반으로 한 코드의 일부입니다. 도움이되기를 바랍니다.

(이 코드를 개선하기 위해 어떤 제안도 자유롭게 제안하십시오.

카운터:

public class InstanceCount{
    private static Map<Integer, CounterInstanceLog> instanceMap = new HashMap<Integer, CounterInstanceLog>();
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);
    }

    (...)
}

그리고 대상 :

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

    (...)



}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

class DBConnection {
    String createdBy = null;

    DBConnection(Throwable whoCreatedMe) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        whoCreatedMe.printStackTrace(pw);
        try {
            createdBy = os.toString();
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable(
                "Connection created from DBConnectionManager");
        DBConnection conn = new DBConnection(createdBy);
        System.out.println(conn.createdBy);
    }
}

또는

public static interface ICallback<T> { T doOperation(); }


public class TestCallerOfMethod {

    public static <T> T callTwo(final ICallback<T> c){
        // Pass the object created at callee to the caller
        // From the passed object we can get; what is the callee name like below.
        System.out.println(c.getClass().getEnclosingMethod().getName());
        return c.doOperation();
    }

    public static boolean callOne(){
        ICallback callBackInstance = new ICallback(Boolean){
            @Override
            public Boolean doOperation() 
            {
                return true;
            }
        };
        return callTwo(callBackInstance);
    }

    public static void main(String[] args) {
         callOne();
    }
}

이 방법을 사용하십시오 :-

 StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
 stackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
 System.out.println(e.getMethodName());

메소드 예제 코드의 발신자는 다음과 같습니다.

public class TestString {

    public static void main(String[] args) {
        TestString testString = new TestString();
        testString.doit1();
        testString.doit2();
        testString.doit3();
        testString.doit4();
    }

    public void doit() {
        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
        System.out.println(e.getMethodName());
    }

    public void doit1() {
        doit();
    }

    public void doit2() {
        doit();
    }

    public void doit3() {
        doit();
    }

    public void doit4() {
        doit();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top