java.lang.Integer cannot be cast to [Ljava.lang.Object;

Michael picture Michael · Apr 20, 2012 · Viewed 10.5k times · Source

I'm currently retrieving data using XML-RPC, this is what I have:

Object[] params = new Object[]{param1, param2};
Object[] obj = new Object[]{};

try {
    obj = (Object[]) client.execute("method.name", params);
} catch (XmlRpcException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 

return obj;

The problem is that sometimes it will return -1 and I'll get this error: java.lang.Integer cannot be cast to [Ljava.lang.Object; - I was wondering if there was a way around this problem?

Answer

Jordão picture Jordão · Apr 20, 2012

You have to check the type of the return value before casting.

Object result = client.execute(...);
if (result instanceof Integer) {
  Integer intResult = (Integer) result;
  ... handle int result
}    
else if (result instanceof Object[]) {
  obj = (Object[]) result;
}
else {
  ... something else
}

I'd be tempted to create a strongly-typed API around these RPC calls. But then again, maybe that's what you're already doing...