Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding an abstract method with generic signature and calling it

Tags:

java

generics

Generic Interface:

public interface Matcher<T> {
    public double getScore(T value1, T value2);
}

Two implementing classes:

public StringMatcher implements Matcher<String> {
    public double getScore(String value1, String value2) {...}
}

public DateMatcher implements Matcher<Date> {
    public double getScore(Date value1, Date value2) {...}
}

So far everything is fine. Replacing T with String or Date isn't a problem. Calling the getScore() method as follows also works:

Matcher<String> matcher = new StringMatcher();
matcher.getScore("hello", "world");

Problems starts when I have a List of unknown Matcher and I want to use the getScore() method.

public void test() {
    List<Matcher<?>> list = new ArrayList<Matcher<?>>();
    list.add(new StringMatcher());
    list.add(new DateMatcher());

    for (Matcher<?> matcher : list) {
        Object value1;
        Object value2;
        //Setting values value1 & value2 appropriate to the current matcher
        matcher.getScore(value1, value2);
    }
}

I can't call matcher.getScore(value1, value2) because it can't handle object parameters. And at this point I have no idea how to solve this. I want to keep the interface and the signatures of the implementing classes with their concrete types. If there is no way around type casting or throwing exceptions that's okay.

like image 703
Frank Wittich Avatar asked Feb 19 '23 01:02

Frank Wittich


1 Answers

You present a conflict between wanting type safety and not wanting it, so you'll just have to decide between them. Calling getScore with Object arguments is obviously type-unsafe.

Now, if you just want a type-unsafe trick to get around compiler/runtime errors, you can declare the list as List<Matcher>, which means you'll be retrieving raw Matchers from it, and then you'll be allowed to pass Objects in. You will get an unchecked cast compiler warning, though.

like image 100
Marko Topolnik Avatar answered Apr 26 '23 23:04

Marko Topolnik