public class Test<T extends Test.Mapper<?>> {
SomeFactory<T> factory;
public Test(SomeFactory<T> factory) {
this.factory = factory;
}
public <V> V handle(T<V> request) { // fails how to get Class<V> of request.getCls() of a mapper or its subtype?
HttpUriRequest httpUriRequest = factory.get(request); // does not work
// decode response and return it as an object represented by request.getCls
return null;
}
public interface Mapper<T> {
Class<T> getCls();
}
public interface SomeMapper<T> extends Mapper<T> {
void doSomeAdditional();
}
public interface SomeFactory<T extends Test.Mapper<?>> {
HttpUriRequest get(T mapper);
}
}
handle 方法是一种通用方法,它执行 http 请求,然后将响应主体解码为由 Mapper 的 getCls() 方法表示的对象。我希望这个类能够处理 Mapper 的不同子类型,因为 SomeFactory 实现需要访问一些仅特定于该类型的方法
与此类似的东西
SomeFactory<SomeMapper<?>> somefactory = // factory implementation
Test<SomeMapper<?>> test = new Test<SomeMapper<?>>(someFactory);
test.handle(implementation of SomeMapper<Integer>); // should return an instance of Integer
澄清:基本上Test的实例化应该只对应于Test的实际类型(SomeMapper或Mapper)的handle()类型。然后,handle 方法可以接受这种实际类型的任何请求。
IE 如果是Test<SomeMapper<?>> test
,我有类似的请求
ASomeMapper implements SomeMapper<Double> {}
BSomeMapper implements SomeMapper<Integer> {}
test.handle(new ASomeMapper()); // this should return Double
test.handle(new BSomeMapper()); // this shold return Integer
也许我应该重新设计?