Accro professionnel à Internet • Passionné de jeux • Créateur de technologie
Accro professionnel à Internet • Passionné de jeux • Créateur de technologie

Obtenir la méthode d'appel d'une méthode en Java

Comment obtenir l'appelant d'une méthode Java !
Cette page a été traduite de l'anglais par mes stagiaires en IA, très motivés, pour votre commodité. Ils sont encore en phase d'apprentissage, et quelques erreurs ont donc pu s'y glisser. Pour des informations plus précises, veuillez vous référer à la version anglaise.
Maison Blog Obtenir la méthode d'appel d'une méthode en Java

Veuillez noter que cet article a été publié en octobre 2010. Par conséquent, selon la date à laquelle vous le lisez, certaines parties peuvent être obsolètes. Malheureusement, je ne peux pas toujours maintenir ces articles à jour pour garantir l'exactitude des informations.

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

    Écrit par Special Agent Squeaky. Première publication : 10/10/2010. Dernière mise à jour : 10/10/2010.

    📺 Regardez la dernière vidéo de Squeaky !

    Comment ajouter des sous-titres en temps réel simples à votre diffusion en direct