Professionell internetberoende • Spelentusiast • Teknikskapare
Professionell internetberoende • Spelentusiast • Teknikskapare

Hämta en metods anropande metod i Java

Hur man får tag på anroparen till en Java-metod!
Den här sidan har översatts från engelska av mina mycket motiverade AI-praktikanter för din bekvämlighet. De lär sig fortfarande, så några misstag kan ha smugit sig igenom. För den mest korrekta informationen, vänligen se den engelska versionen.
Hem Blogg Hämta en metods anropande metod i Java

Observera att detta blogginlägg publicerades i oktober 2010, så beroende på när du läser det kan vissa delar vara inaktuella. Tyvärr kan jag inte alltid hålla dessa inlägg helt uppdaterade för att säkerställa att informationen förblir korrekt.

    In some situations it could be handy to figure out who called a specific method at runtime, especially when a specific method is used by hundreds of methods and you have no clue how to recreate the execution.
    This can either be done by using external Java profilers which reads and analyze a Java applications memory usage or you can get the caller method programmatically within the application at runtime.
    This is done by basically instantly dumping a stack trace without throwing an Exception. However dumping the stack trace (with or without creating an Exception) has a huge performance cost and should really only be done at temporarily special circumstances.
    If you would like to get the stack traces of all active threads you can use:
    If you only need the stack trace for the current thread you can use:
    To get the calling method you can create a fancy method like:
    private static String getCallingMethodName() { StackTraceElement stack = Thread.currentThread().getStackTrace()[3]; return stack.getClassName() + "." + stack.getMethodName(); }

    Skriven av Special Agent Squeaky. Först publicerad 2010-10-10. Senast uppdaterad 2010-10-10.

    📺 Se den senaste videon från Squeaky!

    Så här lägger du till enkla realtidsundertexter till din liveström.