gpt4 book ai didi

java - 在 Java 泛型中处理 类型

转载 作者:行者123 更新时间:2023-12-04 04:45:24 25 4
gpt4 key购买 nike

假设我有一个接口(interface),它描述了可能的请求处理程序,这些处理程序可以在客户端存储的某些客户端 session 状态的上下文中为客户端请求的操作提供服务:

public interface RequestHandler<State> {
// Perform action in the context of currentState and return updated state
public State request(State currentState, String action);
}

为了便于实现 RequestHandlers,我添加了泛型类型 State ,它封装了所有需要的客户端 session 数据。

现在,一个简单的客户端可能如下所示:

public class Client {
private final RequestHandler<?> handler;
private Object state;

Client(RequestHandler<?> handler) {
// Initialize the RequestHandler to use for "go"-requests
this.handler = handler;
// Initialize our client state to "null"
this.state = null;
}

public void go() {
// Execute "go"-request in current state and update state
state = handler.request(state, "go"); // <= this is an error (see below)
}
}

在创建过程中,它会提供一个 RequestHandler ,然后它会使用它来执行“go”请求。它还在私有(private) state 中管理其当前 session 状态的存储。多变的。

现在,由于我的客户不需要担心 session 状态在内部的实际样子,我想使用 RequestHandler<?>如图所示。但是,不幸的是,这给了我 state = handler.request... 中的错误。线:

The method request(capture#3-of ?, String) in the type RequestHandler is not applicable for the arguments (Object, String)



将违规行更改为:

state = ((RequestHandler<Object>) handler).request(state, "go");

(这会将错误变成“未经检查的类型转换”警告)

显然,这样我就放松了对我的 state 的类型检查。 -object,但如果 Client仅将其设置为 nullRequestHandler 返回的内容,应该没有问题吧?

我知道我也可以参数化 ClientClient<State>以及然后使用 State代替 Object?到处。但我宁愿避免这种情况,因为(在我看来)在这种情况下它只是自重,必须随身携带 Client。被实例化或使用...

没有办法投 state(?) , 对?

更新:

如果一切都发生在单个方法而不是类中,那么这个问题有一个很好的解决方案:

public <State> void go(RequestHandler<State> handler) {
State state = null;
state = handler.request(state, "go");
state = handler.request(state, "go again");
state = handler.request(state, "go one more time");
}

这样,我可以在任何地方调用,而不必总是指定 State实际上是。但是整个类没有等效的构造(一些推断的通用参数)吗?

最佳答案

似乎可以制作 Client通用,反射(reflect) RequestHandler 的类型.但是,如果你想在客户端隐藏它,你可以这样做:

public final class Client
{

private final CaptureHelper<?> helper;

<T> Client(RequestHandler<T> handler) {
this.helper = new CaptureHelper<T>(handler);
}

public void go()
{
helper.request("go");
}

private final class CaptureHelper<T>
{

private final RequestHandler<T> handler;

private T state;

private CaptureHelper(RequestHandler<T> handler) {
this.handler = handler;
}

private void request(String action)
{
state = handler.request(state, action);
}

}

}

请注意,这使任何使用客户端的人都不必关心其 RequestHandler 的泛型类型。 .用户会有这样的代码:
RequestHandler<?> handler = ... ;
Client client = new Client(handler); /* Look ma, no generics! */
client.go();

关于java - 在 Java 泛型中处理 <?> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com