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.
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 Matcher
s from it, and then you'll be allowed to pass Object
s in. You will get an unchecked cast compiler warning, though.
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