Common 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 so good. Replacing T with String or Date not a problem. Calling the getScore() method as follows also works:
Matcher<String> matcher = new StringMatcher(); matcher.getScore("hello", "world");
The problems begin when I have a List an 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;
I cannot call matcher.getScore(value1, value2) , because it cannot handle object parameters. And now I have no idea how to solve this. I want to keep the interface and the signatures of the implementation classes with their specific types. If there are no methods associated with type casting or throwing exceptions, that is ok.
source share