स्टैकट्रेस या परावर्तन का उपयोग करके मुझे विधि का कॉलर कैसे मिलेगा?


390

मुझे एक विधि का कॉलर खोजने की आवश्यकता है। क्या स्टैकट्रेस या प्रतिबिंब का उपयोग करना संभव है?


5
बस सोच रहा था, लेकिन आपको ऐसा करने की आवश्यकता क्यों होगी?
जूलियट

2
मेरे पास एक अभिभावक वर्ग (एमवीसी मॉडल) है जो एक नोटिफ़ायर घटना के साथ है और केवल मेरे उपवर्गों के निवासी इस पद्धति को कहते हैं। मैं एक अनावश्यक तर्क के साथ मेरे कोड कूड़े नहीं करना चाहता। मैं बल्कि माता-पिता वर्ग में विधि को उस सेटर का पता लगाने देता हूं जिसने इसे बुलाया था।
सतीश

30
@ सतीश आपको लगता है कि डिजाइन को फिर से सोचना चाहिए
क्रोसनवॉल्ड

7
@ जूलियट कोड के एक बड़े चक को रिफैक्ट करने के हिस्से के रूप में, हाल ही में मैंने एक तरीका बदला है जो कई चीजों द्वारा उपयोग किया जाता है। यह पता लगाने का एक निश्चित तरीका है कि क्या कोड नई पद्धति का ठीक से उपयोग कर रहा था, इसलिए मैं उन मामलों में इसे कॉल करने वाले वर्ग और लाइन नंबर को प्रिंट कर रहा था। लॉगिंग के बाहर, मैं इस तरह से कुछ के लिए कोई वास्तविक उद्देश्य नहीं देखता। हालांकि मैं एपीआई लिखना चाहता हूं कि DontNameYourMethodFooExceptionअगर कॉलिंग विधि का नाम फू है तो इसे फेंक दें ।
क्रंचर

5
मुझे लगता है कि मुझे अपने तरीके के कॉलर को एक अमूल्य डिबगिंग टूल मिल रहा है: जो कि एक वेब खोज ने मुझे यहां लाया। यदि मेरी विधि को कई स्थानों से बुलाया जा रहा है, तो क्या इसे सही समय पर सही स्थान से बुलाया जा रहा है? डिबगिंग या लॉगिंग के बाहर, उपयोगिता शायद सबसे अच्छी तरह से सीमित है, जैसा कि @ क्रंचर उल्लेख है।
ओगरे Psalm33

जवाबों:


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

Javadocs के अनुसार:

सरणी का अंतिम तत्व स्टैक के निचले भाग का प्रतिनिधित्व करता है, जो अनुक्रम में कम से कम हाल ही में विधि मंगलाचरण है।

एक StackTraceElementहै getClassName(), getFileName(), getLineNumber()और getMethodName()

आपको यह निर्धारित करने के लिए प्रयोग करना होगा कि आप कौन सा सूचकांक चाहते हैं (शायद stackTraceElements[1]या [2])।


7
मुझे ध्यान देना चाहिए कि getStackTrace () अभी भी एक अपवाद बनाता है, इसलिए यह वास्तव में तेज़ नहीं है - बस अधिक सुविधाजनक।
माइकल मायर्स

41
ध्यान दें कि यह विधि आपको कॉलर नहीं देगी, लेकिन केवल कॉलर का प्रकार । आपके पास अपने तरीके को कॉल करने वाली वस्तु का संदर्भ नहीं होगा।
जोआचिम सॉयर

3
बस एक साइड नोट, लेकिन 1.5 JVM Thread.currentThread () पर। GetStackTrace () एक नया एक्सेप्शन () (लगभग 3 गुना धीमा) बनाने की तुलना में बहुत धीमा लगता है। लेकिन जैसा कि पहले ही उल्लेख किया गया है, आपको वैसे भी किसी प्रदर्शन-महत्वपूर्ण क्षेत्र में इस तरह कोड का उपयोग नहीं करना चाहिए। ;) एक 1.6 जेवीएम केवल ~ 10% धीमा लगता है और, जैसा कि सॉफ्टवेयर मंकी ने कहा है, यह "नए अपवाद" तरीके से इरादे को बेहतर ढंग से व्यक्त करता है।
GaZ

21
@Eelco Thread.currentThread () सस्ता है। Thread.getStackTrace () महंगा है, क्योंकि Throwable.fillInStackTrace () के विपरीत, कोई गारंटी नहीं है कि विधि उसी थ्रेड द्वारा इसे जांच रही है जिसे कॉल किया जाता है, इसलिए JVM को एक "सेफपॉइंट" बनाना है - ढेर और स्टैक को लॉक करना। इस बग रिपोर्ट को देखें: bugs.sun.com/bugdatabase/view_bug.do?bug_id=6375302
डेविड मोल्स

7
@JoachimSauer क्या आप विधि को कॉल करने वाली वस्तु का संदर्भ प्राप्त करने का एक तरीका जानते हैं?
जोफडे

216

वृद्धि के लिए इस अनुरोध के लिए एक टिप्पणी में एक वैकल्पिक समाधान पाया जा सकता है । यह 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.");
  }
}

जावा 1.6.0_17 पर चलने वाले मेरे 2.4 गीगाहर्ट्ज इंटेल कोर 2 डुओ मैकबुक से आउटपुट का एक उदाहरण:

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() जावा 7 अपडेट 40 में डिफ़ॉल्ट रूप से विधि को अक्षम कर दिया गया है और जावा 8 में पूरी तरह से हटा दिया गया है। जावा बग डेटाबेस में इस मुद्दे में इसके बारे में और पढ़ें

अपडेट २

जैसा कि ज़म्बी ने पाया है, ओरेकल था उस बदलाव को वापस करने के लिए मजबूर किया जिसने हटा दियाsun.reflect.Reflection.getCallerClass() । यह अभी भी जावा 8 में उपलब्ध है (लेकिन इसे हटा दिया गया है)।

अपडेट ३

3 साल बाद: वर्तमान जेवीएम के साथ समय पर अद्यतन।

> 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.

5
हां, ऐसा लगता है। लेकिन ध्यान दें कि उदाहरण में मैं जो समय देता हूं वह एक मिलियन कॉल के लिए है - इसलिए आप इसे कैसे उपयोग कर रहे हैं इसके आधार पर यह एक समस्या नहीं हो सकती है।
जोहान काविंग

1
मेरे लिए मेरी परियोजना से प्रतिबिंब को हटाने से 10x की गति में वृद्धि हुई।
केविन पार्कर

1
हां, सामान्य रूप से प्रतिबिंब धीमा है (उदाहरण के लिए देखें stackoverflow.com/questions/435553/java-reflection-performance ), लेकिन इस विशिष्ट मामले में आंतरिक sun.reflect.Reflection वर्ग का उपयोग सबसे तेज है।
जोहान काविंग

1
यह वास्तव में करने की जरूरत नहीं है। आप लौटे हुए क्लासनाम को प्रिंट करने के लिए ऊपर दिए गए कोड को संशोधित करके इसे सत्यापित कर सकते हैं (और मेरा सुझाव है कि लूप काउंट को 1 तक कम करें)। आप देखेंगे कि सभी विधियाँ समान श्रेणी में आती हैं - TestGetCallerClassName।
जोहान काविंग

1
getCallerClass बहिष्कृत है और 7u40 में निकाल दिया जाएगा .. उदास :(
lyomi

36

ऐसा लगता है कि आप thisविधि के संदर्भ में जाने से बचने की कोशिश कर रहे हैं । thisवर्तमान स्टैक ट्रेस के माध्यम से कॉलर को खोजने की तुलना में पासिंग बेहतर है। एक अधिक ओओ डिज़ाइन के लिए रिफैक्टिंग करना और भी बेहतर है। आपको कॉलर को जानने की आवश्यकता नहीं है। यदि आवश्यक हो तो कॉलबैक ऑब्जेक्ट पास करें।


6
++ कॉल करने वाले को जानना बहुत अधिक जानकारी है। यदि आपको चाहिए, तो आप एक इंटरफ़ेस में पास कर सकते हैं, लेकिन एक अच्छा मौका है कि एक बड़ी रिफैक्टिंग की आवश्यकता है। @ आतिश को अपना कोड पोस्ट करना चाहिए और हमें इसके साथ कुछ मज़े लेने दें :)
बिल के

15
ऐसा करने के लिए मान्य कारण मौजूद हैं। मेरे पास कुछ अवसर हैं जहां मुझे उदाहरण के लिए परीक्षण के दौरान यह मददगार लगा।
इलको

2
@chillenious मुझे पता है :) मैंने ऐसा करने के लिए एक विधि बनाई है LoggerFactory.getLogger(MyClass.class)जहाँ मुझे कक्षा शाब्दिक में पास नहीं होना था। यह अभी भी शायद ही कभी सही बात है।
क्रेग पी। मोटलीन

6
यह सामान्य रूप से अच्छी सलाह है, लेकिन यह सवाल का जवाब नहीं देता है।
नवीन

1
जब यह .NET INotifyPropertyChangedइंटरफ़ेस लागू करते समय कॉलर के बारे में जानकारी प्राप्त करने के लिए सही डिज़ाइन निर्णय हो सकता है, तो इसका एक ठोस उदाहरण । हालांकि यह विशिष्ट उदाहरण जावा में नहीं है, वही समस्या तब प्रकट हो सकती है जब रिफ्लेक्शन के लिए स्ट्रिंग्स के रूप में फ़ील्ड / गेटर्स को मॉडल करने की कोशिश की जाती है।
क्रिस केरेक्स

30

जावा 9 - जेईपी 259: स्टैक-वॉकिंग एपीआई

जेईपी 259 स्टैक वॉकिंग के लिए एक कुशल मानक एपीआई प्रदान करता है जो स्टैक ट्रेस की जानकारी को आसान फ़िल्टरिंग और आलसी पहुंच की अनुमति देता है। स्टैक-वॉकिंग एपीआई से पहले, स्टैक फ्रेम तक पहुंचने के सामान्य तरीके थे:

Throwable::getStackTraceऔर ऑब्जेक्ट Thread::getStackTraceकी एक सरणी लौटाते StackTraceElementहैं, जिसमें प्रत्येक स्टैक-ट्रेस तत्व का वर्ग नाम और विधि का नाम होता है।

SecurityManager::getClassContext एक संरक्षित तरीका है, जो अनुमति देता है a SecurityManager उपवर्ग को वर्ग के संदर्भ तक पहुंचने की ।

JDK- आंतरिक sun.reflect.Reflection::getCallerClassविधि जिसे आपको किसी भी तरह से उपयोग नहीं करना चाहिए

इन एपीआई का उपयोग करना आमतौर पर अक्षम हैं:

इन एपीआई को पूरे स्टैक के स्नैपशॉट पर उत्सुकता से कब्जा करने के लिए वीएम की आवश्यकता होती है , और वे पूरे स्टैक का प्रतिनिधित्व करने वाली जानकारी वापस करते हैं। सभी फ़्रेमों की जांच करने की लागत से बचने का कोई तरीका नहीं है यदि कॉलर केवल स्टैक पर शीर्ष कुछ फ़्रेमों में रुचि रखता है।

तत्काल कॉलर की कक्षा खोजने के लिए, पहले एक प्राप्त करें StackWalker:

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

फिर या तो कॉल करें getCallerClass():

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

या रों और पहले पूर्ववर्ती :walkStackFrameStackFrame

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

15

ऑनलाइनर :

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

ध्यान दें कि आपको 2 को 1 से बदलने की आवश्यकता हो सकती है।


10

यह विधि एक ही काम करती है, लेकिन थोड़ा और सरल और संभवतः थोड़ा अधिक प्रदर्शन करने वाली और उस घटना में जब आप प्रतिबिंब का उपयोग कर रहे होते हैं, तो यह अपने आप अपने फ्रेम को छोड़ देता है। एकमात्र मुद्दा यह है कि यह गैर-सूर्य जेवीएम में मौजूद नहीं हो सकता है, हालांकि यह 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 वीएम संस्करणों का java.lang.System, एक पैकेज संरक्षित तरीका है जिसे गेटकैलरक्लास () कहा जाता है sun.reflect.Reflection.getCallerClass(3), जो कॉल करता है , लेकिन मेरी सहायक उपयोगिता वर्ग में मैंने 4 का इस्तेमाल किया क्योंकि हेल्पर क्लास का जोड़ा फ्रेम है मंगलाचरण।


16
जेवीएम कार्यान्वयन कक्षाओं का उपयोग वास्तव में एक बुरा विचार है।
लॉरेंस Dol

7
का उल्लेख किया। मैंने निर्दिष्ट किया कि यह एक सार्वजनिक वर्ग नहीं है, और java.lang.System में संरक्षित विधि getCallerClass () सभी 1.5+ VMs में मौजूद है, जिन्हें मैंने आईबीएम, JRockit और Sun सहित देखा है, लेकिन यह दावा रूढ़िवादी ध्वनि है ।
निकोलस

6
@ शेफ़र मंकी, हमेशा की तरह, "यह सब निर्भर करता है"। डिबगिंग या टेस्ट लॉगिंग में सहायता करने के लिए ऐसा कुछ करना - खासकर अगर यह उत्पादन कोड में कभी समाप्त नहीं होता है - या यदि तैनाती लक्ष्य सख्ती से डेवलपर के पीसी है, तो शायद ठीक हो जाएगा। कोई भी जो अभी भी अन्यथा इस तरह के मामलों में भी सोचता है: आपको वास्तव में " वास्तव में बुरा विचार" समझाने की आवश्यकता होगी यह कहने से बेहतर है कि यह बुरा है ...

8
इसके अलावा, इसी तरह के तर्क से आप यह भी तर्क दे सकते हैं कि कभी भी आप हाइबरनेट-विशिष्ट सुविधा का उपयोग करते हैं जो कि जेपीए संगत नहीं है, यह हमेशा एक " वास्तव में बुरा विचार" है। या यदि आप ओरेकल-विशिष्ट सुविधाओं का उपयोग करने जा रहे हैं जो अन्य डेटाबेस में उपलब्ध नहीं हैं, तो यह " वास्तव में बुरा विचार" है। यकीन है कि यह एक सुरक्षित मानसिकता है और निश्चित उपयोग के लिए निश्चित रूप से अच्छी सलाह है, लेकिन स्वचालित रूप से उपयोगी उपकरणों को सिर्फ इसलिए फेंक दिया जाता है क्योंकि यह एक सॉफ्टवेयर कॉन्फ़िगरेशन के साथ काम नहीं करेगा जो आप कर रहे हैं, उह .. बिल्कुल उपयोग नहीं कर रहे हैं ? वह थोड़ा बहुत अनम्य और थोड़ा मूर्ख है।

5
विक्रेता विशिष्ट वर्गों का असमान उपयोग समस्याओं की एक उच्च संभावना प्रस्तुत करेगा, लेकिन किसी को यदि प्रश्न में वर्ग मौजूद नहीं है (या किसी कारण से निषिद्ध है) तो इनायत से नीचा दिखाने का मार्ग निर्धारित करना चाहिए। किसी भी विक्रेता विशिष्ट वर्गों का उपयोग करने के लिए फ्लैट-आउट मना करने की नीति, मेरी राय में, थोड़ा भोला है। उत्पादन में उपयोग किए जाने वाले कुछ पुस्तकालयों के स्रोत कोड में चारों ओर प्रहार करें और देखें कि क्या उनमें से कोई भी ऐसा करता है। (sun.misc.Unsafe शायद?)
निकोलस

7
     /**
       * 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;
      }

मुझे जावा 1.4 के साथ काम करने वाली चीज़ की ज़रूरत थी और यह उत्तर बहुत मददगार था! धन्यवाद!
RGO

6

मैंने पहले भी ऐसा किया है। आप बस एक नया अपवाद बना सकते हैं और इसे फेंकने के बिना स्टैक ट्रेस को पकड़ सकते हैं, फिर स्टैक ट्रेस की जांच कर सकते हैं। जैसा कि अन्य उत्तर में कहा गया है, यह बेहद महंगा है - तंग पाश में मत करो।

मैंने इसे पहले एक ऐप पर लॉगिंग यूटिलिटी के लिए किया है, जहां प्रदर्शन बहुत ज्यादा मायने नहीं रखता था (प्रदर्शन शायद ही कभी बहुत ज्यादा मायने रखता है, वास्तव में - जब तक आप एक कार्रवाई का परिणाम प्रदर्शित करते हैं जैसे कि बटन पर क्लिक करें जल्दी से)।

इससे पहले कि आप स्टैक ट्रेस प्राप्त कर सकते थे, अपवादों में सिर्फ .printStackTrace () था, इसलिए मुझे अपने स्वयं के निर्माण की एक प्रणाली पर पुनर्निर्देशित करना था, फिर (नया अपवाद ())। PrintStackTrace (); सिस्टम पुनर्निर्देशित करें। वापस स्ट्रीम करें और स्ट्रीम पार्स करें। मजेदार चीजें।


ठंडा; आपको इसे फेंकना नहीं है?
krosenvold

नहींं, कम से कम यह है कि मैं इसे कैसे याद रखूं, मैंने इसे कुछ वर्षों में नहीं किया है, लेकिन मुझे पूरा यकीन है कि अपवाद को नया बनाना केवल एक ऑब्जेक्ट बनाना है, और अपवाद को फेंकना इसके अलावा कुछ भी नहीं करता है यह पकड़ () खंड के लिए।
बिल K

साफ। मैं एक वास्तविक अपवाद का अनुकरण करने के लिए इसे फेंकने पर झुका हुआ था।
सतीश

नहीं, Java 5 के बाद से थ्रेड पर एक विधि है StackTraceElements की एक सरणी के रूप में वर्तमान स्टैक प्राप्त करने के लिए; यह अभी भी सस्ता नहीं है, लेकिन पुराने अपवाद-पार्सिंग समाधान से सस्ता है।
लॉरेंस डोल

@ शेफ बंदर हालांकि मुझे यकीन है कि यह अधिक उपयुक्त है, आप क्या कहते हैं कि यह सस्ता है? मुझे लगता है कि एक ही तंत्र का उपयोग किया जाएगा, और यदि नहीं, तो एक ही काम क्यों करें जब यह एक ही काम करता है?
बिल K

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

0

यहां उस कोड का एक हिस्सा है जो मैंने इस विषय में दिखाए गए संकेतों के आधार पर बनाया है। आशा है ये मदद करेगा।

(इस कोड को बेहतर बनाने के लिए कोई सुझाव देने के लिए स्वतंत्र महसूस करें, कृपया मुझे बताएं)

काउंटर:

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

    (...)



}

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

0

इस विधि का उपयोग करें: -

 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();
    }
}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.