Addicte professional a Internet • Entusiasta dels videojocs • Creador de tecnologia
Addicte professional a Internet • Entusiasta dels videojocs • Creador de tecnologia

Com obtenir el mètode que ha cridat un altre mètode en Java

Com obtenir qui ha cridat un mètode Java!
Aquesta pàgina ha estat traduïda de l'anglès pels meus becaris d'IA, altament motivats, per a la vostra comoditat. Encara estan aprenent, així que és possible que s'hagin escapat alguns errors. Per obtenir la informació més precisa, consulteu la versió anglesa.
Inici Bloc Com obtenir el mètode que ha cridat un altre mètode en Java

Aquesta entrada és de l’octubre de 2010 — potser hi ha parts que han quedat una mica velles, però continua tenint valor històric!

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

    Escrit per Special Agent Squeaky. Publicat per primera vegada el 10-10-2010. Última actualització el 10-10-2010.

    📺 Mira l'últim vídeo de Squeaky!

    Com afegir subtítols en temps real simples a la teva transmissió en directe