我一直在尝试破译Java的Alexa智能家居指令API,并且遇到了我从未见过的结构,无法弄清楚如何在搜索中引用它。我知道泛型,但这显然是不同的(至少我认为)。有人可以向我解释使用<Req extends Request <Res>, Res extends Response>
的受保护方法声明中发生了什么吗?
public abstract class SmartHomeDirectiveHandler implements
RequestStreamHandler {
private static Gson gson = new Gson();
private static HandlerFactory factory = new HandlerFactory();
protected <Req extends Request<Res>, Res extends Response> void
registerHandler(MessageName name,RequestHandler<Req, Res> handler) {
factory.registerHandler(name, handler);
}
abstract protected void init();
protected SmartHomeDirectiveHandler() {
this.init();
}
public final void handleRequest(InputStream inputStream, OutputStream
outputStream, Context context) throws IOException {
JsonReader reader = new JsonReader(new
InputStreamReader(inputStream));
SmartHomeDirectiveRequest request = gson.fromJson(reader,
SmartHomeDirectiveRequest.class);
RequestHandler handler =
factory.getHandler(request.getHeader().getName());
Request req = PayloadDeserializer.deserializePayload(request);
Response responsePayload;
try {
responsePayload = handler.handle(req);
} catch (Exception e) {
throw new IOException(e);
}
SmartHomeDirectiveResponse response = new
SmartHomeDirectiveResponse();
Header responseHeader = new Header();
responseHeader.setName(responsePayload.getMessageName());
responseHeader.setMessageId(request.getHeader().getMessageId());
responseHeader.setPayloadVersion(request.getHeader()
.getPayloadVersion());
responseHeader.setNamespace(request.getHeader().getNamespace());
response.setHeader(responseHeader);
response.setPayload(responsePayload);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
writer.write(gson.toJson(response,
SmartHomeDirectiveResponse.class));
writer.flush();
}
}
答案 0 :(得分:3)
为简化答案,定义了具有通用参数的方法,如下所示:
public <T> void methodName(T parameterName){
//stuff
}
在您的情况下,该方法具有两种通用类型,因此(再次简化)为:
public <T,E> void methodName(T parameterName, E parameterTwoName){
//stuff
}
最后,这些泛型具有上限,因此结果:
public <T extends Request<E> ,E extends Response > void methodName(T parameterName, E parameterTwoName){
//stuff
}