How to check if a Java Class is part of the current stack trace?

北慕城南 提交于 2021-01-27 21:20:52

问题


I have a class:

MessageReceiver.java

that receives messages but can also produce messages indirectly (that then could potentially be redelivered to this class). I don't want to process messages that were sent with MessageReceiver.java in the stack trace. Is there a way to efficiently determine if the message I received was from MessageReceiver.java?

The following chain is possible:

MessageReceiver.java -> OtherClass.java -> MessageProducer.java -> MessageReceiver.java

回答1:


I think this is what you're after:

Class<?> myClass = MessageReceiver.class;
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

for (StackTraceElement element : stackTrace) {
    if (element.getClassName().equals(myClass.getCanonicalName())) {
        System.out.println("class found in stack trace");
        break;
    }
}



回答2:


You could add a custom header to the message that indicates the original emitter. So MessageReceiver will emit messages by setting the header value to "MessageReceiver", and will discard all messages that have this specific header value.




回答3:


You could get the stacktrace from the Exception and simply loop them comparing class names.

Exception.getStackTrace() returns an array of StackTraceElements, which has a getClassName method.

http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace() http://docs.oracle.com/javase/6/docs/api/java/lang/StackTraceElement.html

Assuming I understood the question



来源:https://stackoverflow.com/questions/11414782/how-to-check-if-a-java-class-is-part-of-the-current-stack-trace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!