java异步返回结果,Java-具有返回值的异步方法

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

The situation is the following:

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

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?

解决方案

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.

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 getResponse() {

return (T)response;

}

public void setResponse(T response) {

this.response = response;

}

}

Usage:

IResponseListener listener = new IResponseListener() {

public void response(ResponseEvent event) {

float f = event.getResponse();

}

};

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值