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;
}
});
}
You should think of Java generic types as annotations for the compiler, rather than something that you can use in code, because they don't exist at bytecode level.
If you need to check for a type, you must pass the class to the method.
This should work:
private ServerEvent filterEvents(final Class<?> clazz) {
return argThat(new ArgumentMatcher<ServerEvent>() {
@Override
public boolean matches(Object argument) {
return clazz.isInstance(argument);
}
});
Edit:
Java's instanceof
operator can not compare an object against a class reference. It requires the class name. Class.isInstance()
allows you to check instances dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With