Reputation: 49107
I have a question regarding what is the correct method signature in the interface, and why. My event is parameterized with a type, however should the interface also have a <T>
which uses it in the method signature? If so why, why not?
public interface MyListener {
void beforeAction(final MyEvent event);
}
And
public class MyEvent<T> extends EventObject {
// code
}
Upvotes: 3
Views: 72
Reputation: 88757
If the type of T
doesn't matter in your listener, you should at least define the method as void beforeAction(final MyEvent<?> event);
in order to get rid of the warning and keep generics enabled. Without any type, the compiler will disable all type checks for that method.
If you want to have different listeners for different types of events, you should add the T
to your interface as well, like Andrew already pointed out.
This way you could create several listener implementations without the need for manual casts (and thus bugs), e.g. something like this:
public class StringListener implements MyListener<String> {
void beforeAction(final MyEvent<String> event) {
...
}
}
public class NumberListener implements MyListener<Number> {
void beforeAction(final MyEvent<Number> event) {
...
}
}
If you have implementations like this, you could also query the value of T
at runtime, since that type information is stored in the reflection data.
Note that this isn't true for anonymous classes or local variables - in those cases type erasure takes place.
Upvotes: 2
Reputation: 36940
If MyEvent
is parameterized with a type, then MyListener
will need to be specified as either
public interface MyListener<T> {
void beforeAction(final MyEvent<T> event);
}
or if there are different types of MyEvents
that are not specific to the enclosing MyListener
, then:
public interface MyListener {
<T> void beforeAction(final MyEvent<T> event);
}
Or, as Thomas said, you can just ignore the type of T altogether:
public interface MyListener {
void beforeAction(final MyEvent<?> event);
}
You will have to do one of the above, or you will get a compiler warning about using raw types.
Upvotes: 5