Java-具有返回值的异步方法 [英] Java - asynchronous methods with return value

查看:897
本文介绍了Java-具有返回值的异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的异步方法调用有疑问,尤其是关于异步方法的响应值。

I have a question about asynchronous method calls in java, especially about the response value of the async method.

情况如下:

我要调用的异步方法是..

The async method I want to call is..

public void getSpeed(IResponseListener listener) {
....
}

侦听器的界面是...

The interface of the listener is...

interface IResponseListener {
    public void response(ResponseEvent event);
}

当异步方法具有响应值时调用此方法

This method is called when the async method has a response value

我现在的问题是,类 ResponseEvent 具有一个属性 response 可以是任何类型(布尔值,浮点数,字符串...),并且在接口 IResponseListener 的实现中必须强制转换值...

My problem now is that the class ResponseEvent has an attribute response that can be of any type (boolean,float,String...)and in the implementation of the interface IResponseListener I have to cast the value...

IResponseListener listener = new IResponseListener {

    public void response(ResponseEvent event) {
        float f = (float)event.response;
    }
}

这是解决此问题的好方法吗?我认为不好的是,响应侦听器必须知道响应的类型!
是否有更好的解决方案来处理想要给出响应的异步调用,即使响应可以是任何类型?

Is this a good solution to handle this? I think the bad thing is that the response listener HAS to know the type of the response! Is there a better solution to handle asynchronous calls that want to give a response even if the response can be of any type?

推荐答案

我会按照@nico_ekito所说的那样做...或者使用您现有的解决方案。这是一个您不知道结果类型的问题。

I would have done as @nico_ekito says...Or use your existing solution. It is a problem that you don't know the result type.

无论如何,您可以进行一些调整,然后让ResponseEvent类为您进行转换。

Anyway, you could do some adjustments and let the ResponseEvent class do the casting for you.

ResponseListener.java

interface IResponseListener {
    void response(ResponseEvent event);
}

ResponseEvent.java

public class ResponseEvent {

   private Object response;

   @SuppressWarnings("unchecked")
   public <T> T getResponse() {
       return (T)response;
   }

   public <T> void setResponse(T response) {
       this.response = response;
   }
}

用法:

IResponseListener listener = new IResponseListener() {
    public void response(ResponseEvent event) {
        float f = event.getResponse();
    } 
};

请注意,您将获得 ClassCastException 如果您的类型不是您期望的类型。

Please note that you will get a ClassCastException if your type is something other than what you expect it to be.

这篇关于Java-具有返回值的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆