java - 通过使用动态代理,有没有办法返回一个类型与代理接口(interface)的方法签名不匹配的对象?

标签 java netty

我认为简短的回答可能是否定的,但我希望我能得到其他建议。假设我有一个数据对象和一个数据服务。数据服务是一个接口(interface),具有以下方法。

public Data getData();

我正在使用以下调用处理程序和 Netty 为服务创建代理,以执行我称之为异步 rpc 的操作。代理在客户端。

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // Convert the call into an async request that returns a ListenableFuture
    APCRequest request = new APCRequest(serviceType, method, args);
    ListenableFuture future = apcClient.asyncMessage(request);

    // This blocks until the future finishes
    return future.get();
}

这很好用。但是,如果我的客户端是一个 UI,我最终会将服务调用包装在类似 SwingWorker 的东西中。我更愿意想出一种方法来返回我已经坐在那里的 ListenableFuture。有什么方法可以在不创建单独的异步服务 API 的情况下实现这一目标。例如:

public ListenableFuture<Data> getData();

如果我可以让我的 InvocationHandler 返回错误的类型,我可以使用类似这样的东西。

public abstract class AsyncServiceCall<S, D> { // S = service type, D = expected doCall return type
    protected final S service;

    protected AsyncServiceCall(Class<S> serviceType, APCClient client) {
        ProxyFactory proxyFactory = new ProxyFactory(client);

        // The true tells the proxyFactory we're expecting a ListenableFuture<D>
        // rather than the real return type.
        service = proxyFactory.createProxy(serviceType, true);
    }

    // Sub-classes would make a normal method call using this.  For
    // example, service.getData()
    public abstract Object doCall();

    @SuppressWarnings("unchecked")
    public ListenableFuture<D> execute() {
        return (ListenableFuture<D>) doCall();
    }

还有其他方法可以实现我想要的吗?性能对我来说不是问题,所以如果没有简单的方法来做我想做的事情,那么阻塞直到代理可以从 future 获得返回值仍然是一种选择。这似乎是一种浪费,因为无论如何我都想在 UI 中进行异步调用。

保持我的服务 API 简单比什么都重要。我希望能够使用一个简单的服务提供者来制作原型(prototype),该服务提供者直接实例化服务实现,并在开发周期后期插入使用动态代理/Netty 的远程处理协议(protocol)/服务器。

最佳答案

如果您想保持 API 简单,那么我建议在接口(interface)中提供异步 API - 在异步 API 中封装同步实现比反之更容易。

public interface DataService {
  public ListenableFuture<Data> getData();
}

public abstract class LocalDataService implements DataService {
  public ListenableFuture<Data> getData() {
    SettableFuture<Data> result = SettableFuture.create();
    try {
      Data theData = computeData();
      result.set(theData);
    } catch(Throwable t) {
      result.setException(e);
    }
    return result;
  }

  protected abstract Data computeData() throws Throwable;
}

关于java - 通过使用动态代理,有没有办法返回一个类型与代理接口(interface)的方法签名不匹配的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590890/

相关文章:

java - 从其他类实例化时 JPanel 未打开

java - Netty 服务器如何向不同的客户端发送数据?

java - Netty 中多种数据包类型的解码和编码

java - Netty SSL header

java - Netty 使用数据库连接和查询?

java - Netty 4.x中服务器没有实现客户端发送的消息

java - Kotlin 中无法使用 CameraKit 拍照

java - 当我发现自己是 "over-casting"时该怎么办?

java - 从 Java 调用 Clojure : java. lang.NumberFormatException: null

java - 在 EMR 上提交 JAR 时出现 ClassNotFoundException