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.