كيف أجد المتصل للطريقة باستخدام stacktrace أو الانعكاس؟

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

  •  05-07-2019
  •  | 
  •  

سؤال

أحتاج إلى العثور على المتصل للطريقة. هل من الممكن استخدام stacktrace أو انعكاس؟

هل كانت مفيدة؟

المحلول

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.4 جيجا هرتز 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 يبدو أن الأسرع.

تحديث

كما ليومي يشير في هذا التعليق ال sun.reflect.Reflection.getCallerClass() تم تعطيل الطريقة افتراضيًا في تحديث Java 7 40 وإزالتها بالكامل في Java 8. اقرأ المزيد حول هذا الموضوع في هذه المشكلة في قاعدة بيانات Java Bug.

تحديث 2

كما زمبي لقد وجد ، كان أوراكل أجبر على العودة من التغيير التي أزالت 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 أكثر. يجب ألا تحتاج إلى معرفة المتصل. تمرير كائن رد الاتصال إذا لزم الأمر.

Java 9 - JEP 259: API المشي مكدس

JEP 259 يوفر واجهة برمجة تطبيقات قياسية فعالة للمشي المكدس التي تتيح التصفية السهلة للمعلومات والوصول الكسول إليها. قبل واجهة برمجة تطبيقات المشي المكدس ، كانت الطرق الشائعة للوصول إلى إطارات المكدس:

Throwable::getStackTrace و Thread::getStackTrace إعادة مجموعة من StackTraceElement الكائنات ، التي تحتوي على اسم الفئة واسم طريقة كل عنصر تتبع المكدس.

SecurityManager::getClassContext هي طريقة محمية ، والتي تسمح SecurityManager الفئة الفرعية للوصول إلى سياق الفصل.

JDK-Internal sun.reflect.Reflection::getCallerClass الطريقة التي يجب ألا تستخدمها على أي حال

عادة ما يكون استخدام واجهات برمجة التطبيقات هذه غير فعال:

تتطلب واجهات برمجة التطبيقات هذه 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());

oneliner:

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

لاحظ أنك قد تحتاج إلى استبدال 2 بـ 1.

تقوم هذه الطريقة بنفس الشيء ولكن بكل بساطة وربما أكثر من أداء أكثر بقليل ، وفي حالة استخدامك الانعكاس ، فإنه يتخطى تلك الإطارات تلقائيًا. المشكلة الوحيدة هي أنه قد لا يكون موجودًا في JVMs غير SUN ، على الرغم من أنه يتم تضمينه في فئات وقت التشغيل في JRockit 1.4-> 1.6. (النقطة هي ، إنها ليست ملف عام صف دراسي).

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 يجب أن تكون القيمة ، إصدارات الشمس 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();
      }

على سبيل المثال ، إذا حاولت الحصول على خط طريقة الاتصال لغرض التصحيح ، فأنت بحاجة إلى تجاوز فئة الأداة المساعدة التي ترمز إليها تلك الأساليب الثابتة:
(رمز Java1.4 القديم ، فقط لتوضيح استخدام StackTraceElement المحتمل)

        /**
          * 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 () لذلك اضطررت إلى إعادة توجيه النظام. إعادة توجيه النظام. متعة الاشياء.

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());

رمز مثال Method Method هنا:-

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