Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a java method with generic class type?

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;
        }
    });
}
like image 864
Elad Benda Avatar asked Jan 10 '23 14:01

Elad Benda


1 Answers

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.

like image 193
Tim Jansen Avatar answered Jan 20 '23 07:01

Tim Jansen