I want to write a generic method (either with generics or with param)
that will replace these two calls:
private ServerEvent filterEvents() {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return argument instanceof Type1;
}
});
private ServerEvent filterEvents() {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return argument instanceof Type2;
}
});
I have tried this, but got compilation errors:
private <T> ServerEvent filterEvents() {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return argument instanceof T;
}
});
update:
I have tried this also, but still got compiliation error:
verify(loggerUtilsWrapper).writeEvent(filterEvents(MatchNotFoundEvent.class));
private ServerEvent filterEvents(final Class<MatcherEvent> eventType) {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return argument instanceof eventType;
}
});
}
Due to runtime type erasure, the "T" is not available. The standard way is to pass a type token by way of a parameter of type Class<T>
.
However, in this case you don't need generic, because you aren't actually using the type. Instead, just pass a Class object and compare it:
private ServerEvent filterEvents(final Class<?> c) {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return c.isInstance(argument);
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments