问题
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