0

I have a listening method that waits for a FooBarEvent in the Dummy class:

@Subscribe
public void testingEvents(FooBarEvent event) {

}

On the other hand, I have a class that needs that method :

public class TestEvents{
    public TestEvents(event){
        FooBarEvent event = new FooBarEvent (...);
        event.post(event);
    }
}

This is called from the main class which acts like this :

EventBus bus = new EventBus();
bus.register(new Dummy());

The question is : How can get, at the testingEvents(the subscriber), the class that posted the events?.

(As a result, I'm expecting to get at that method that the caller is the TestEvents class).

Thank you.

Fredo
  • 1
  • 1

1 Answers1

3

In most code I've seen, it's the events themselves that have a source field indicating where the event originated. Can you just add a field to FooBarEvent that either contains the source object (or just the class of the source, if it's all you need)?

Paul Blessing
  • 3,815
  • 2
  • 24
  • 25
  • Your answer is clearly correct. But, I wonder if the `EventBus` has an out-of-the-box mechanism that would allow to get the event's source. – Fredo May 25 '12 at 06:21
  • (Indeed, how would you _possibly_ implement such a feature?) – Louis Wasserman May 25 '12 at 07:50
  • (You could access it using reflection but that would be ugly and slow: http://stackoverflow.com/questions/421280/in-java-how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection ) – Etienne Neveu May 25 '12 at 13:11