我有以下示例 Java 程序,它在 Oracle JDK 下编译得很好,但在 OpenJDK 上编译得不好:
public class GenericsBug {
public static void main(String[] args) {
GenericsBug bug = new GenericsBug();
// This line causes the error for not finding matching types:
AResp resp = bug.execute(new AReq());
}
public <T extends Request,R extends Response<T>> R execute(T request) {
return null;
}
}
class Request { }
class Response<T extends Request> {}
class AReq extends Request {}
class AResp extends Response<AReq> {}
编译它
java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04-415-11M3635)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode)
和
java version "1.7.0_03"
OpenJDK Runtime Environment (IcedTea7 2.1.1pre) (7~u3-2.1.1~pre1-1ubuntu3)
OpenJDK Client VM (build 22.0-b10, mixed mode, sharing)
工作正常,但失败
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.13) (6b18-1.8.13-0+squeeze1)
OpenJDK 64-Bit Server VM (build 14.0-b16, mixed mode)
我在这里得到以下编译错误:
GenericsBug.java:9: type parameters of <R>R cannot be determined; no unique maximal instance exists for type variable R with upper bounds AResp,Response<T>
AResp resp = bug.execute(new AReq());
^
1 error
所以我的问题是,如果这是 OpenJDK 中的一个错误,还是我在泛型类型推断方面做错了什么?
因为在下面的评论中,有一些关于这段代码有用性的问题(尽管这个问题纯粹是与语法相关的 ;-),这里是给出的示例,其中包含更多内容。它使用双重调度让请求自己创建响应,并使用参数化执行使使用尽可能类型安全,只允许相同的请求和响应类型对。同样的场景也可以用多个重载execute()
方法来完成。不管这段代码是否有用,关于这个用例的 Oracle JDK 和 OpenJDK 1.6 之间的不同语法处理的问题仍然存在。
public class Client {
public static void main(String[] args) {
Client client = new Client();
// AReq and AResp must match, otherwise an compile error will happen
AResp respA = client.execute(new AReq());
System.out.println(respA.getAContent());
// Same for BReq and BResp
BResp respB = client.execute(new BReq());
System.out.println(respB.getBContent());
}
public <T extends Request,R extends Response<T>> R execute(T request) {
// Fetch the response somehow, eg. by using a HttpClient:
String responseBody = "....";
// Let the request itself create the response
return request.createResponse(responseBody);
}
}
// ==================================================================================
// Abstract definition of a requests
abstract class Request {
abstract <R extends Response<? extends Request>> R createResponse(String content);
}
class Response<T extends Request> {}
// Two request/response pairs with specific request/response specific members
class AReq extends Request {
AResp createResponse(String content) {
return new AResp(content);
}
}
class AResp extends Response<AReq> {
private String aContent;
public AResp(String pContent) {
aContent = "AResp: " + pContent;
}
public String getAContent() {
return aContent;
}
}
class BReq extends Request {
BResp createResponse(String content) {
return new BResp(content);
}
}
class BResp extends Response<BReq> {
private String bContent;
public BResp(String pContent) {
bContent = "BResp: " + pContent;
}
public String getBContent() {
return bContent;
}
}