DaveAKing / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

EventBus interacts poorly with generics #1431

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
When a generic type is posted to the event bus, type erasure means that 
handlers for the same type with different parameters are invoked unexpectedly. 
The following test causes a ClassCastException:

  @Test
  public void test() {
    EventBus eventBus = new EventBus();
    eventBus.register(this);
    eventBus.post(ImmutableList.of("one", "two"));
  }

  @Subscribe
  public void handle(List<Integer> e) {
    System.out.println(e.get(0) + 1);
  }

Language restrictions probably make it impossible to handle this case 
correctly, but maybe EventBus could do something like notice if two handlers 
are being registered for the same erased type (but different declared types) 
and display a warning?

Original issue reported on code.google.com by ekuef...@gmail.com on 26 May 2013 at 3:18

GoogleCodeExporter commented 9 years ago
Hi,
you are right, you will not be able to distinguish between different types of 
generic lists after compilation because Java generics are erasure type. I think 
the issue can be closed as there is no way to fix it.

Besides, I think it makes little sense to post List<Integer> to the event bus 
anyway. You will not be able to use this type for some other purpose and it 
contains no information on what kind of integers are inside. You will not be 
able to add a comment to it. You are much better of posting events containing 
the list. For example:
/** Magic numbers have changed! @see MagicNumbers */
class MagicNumbersChanged {
    public final List<Integer> numbers;
}

In this case you will be able to access the numbers as a generic list and at 
the same time you will be able to have different event types using 
List<Integer>.

BR,
Yuriy

Original comment by Yuriy.Kulikov.87@gmail.com on 14 Sep 2014 at 2:52

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:12

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:17

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08