我有这个设计,我不确定为什么它不起作用。
interface BaseType {}
interface TypeA extends BaseType {}
interface TypeB extends BaseType {}
interface Query<T extends BaseType> {
public String get();
}
interface Result<T extends BaseType> {
public String get();
}
interface Service<T extends BaseType> {
public Result<T> get(Query<T> query);
}
class SomeResult implements Result<TypeA> {
private String s;
public SomeResult(String s) { this.s = s; }
public String get() { return this.s; }
}
class SomeQuery implements Query<TypeA> {
public String get() { return "blah"; }
}
class SomeQuery2 implements Query<TypeA> {
public String get() { return "blah2"; }
}
class SomeService implements Service<TypeA> {
/** OK -- but notice the ambiguous parameter type */
/*
public SomeResult get(Query<TypeA> query) {
if (query instanceof SomeQuery) return new SomeResult(query.get());
else return null;
}
*/
/** NOT OK -- but this is the parameter I want to keep; notice SomeQuery IS-A Query<TypeA> */
public SomeResult get(SomeQuery query) { return new SomeResult(query.get()); };
/**
* Main.java:27: error: SomeService is not abstract and does not override abstract method get(Query<TypeA>) in Service
* class SomeService implements Service<TypeA> {
* ^
* 1 error
*/
}
public class Main {
public static void main(String args[]) {
SomeQuery someQuery = new SomeQuery();
SomeQuery2 someQuery2 = new SomeQuery2();
SomeService someService = new SomeService();
System.out.println(someService.get(someQuery).get());
}
}
我是仿制药新手,不太明白我在这里违反了什么合同。我希望服务受到严格限制,即使我可以绑定返回类型,我似乎也无法为参数这样做。这意味着,我需要instanceof
在服务内部进行检查,以确保获得正确的参数。我想避免这种情况。有任何想法吗?