1

I have a method that contacts web service, parse and return an array of custom objects. The service will also pack some error message in the response some times.

I want my method while returning the array of custom objects, should able to update error message when available on something similar to output parameters.

It appears Java does not support out parameters. In objective-C, many methods takes pointer like &error as a last argument to update the error.

Is there a way to achieve this in Java?

Saran
  • 6,274
  • 3
  • 39
  • 48
  • You need a class, that has two properties, one of which is your return value, and the other is your error. A couple if you will, a specific case of a Tuple. – Benjamin Gruenbaum Mar 28 '13 at 18:50
  • first hit on google for 'java out parameters' http://stackoverflow.com/questions/2824910/how-to-use-an-output-parameter-in-java – Colin D Mar 28 '13 at 18:53
  • Can't you use checked exceptions here? Create a custom exception for being thrown by your method at the end of your method. I assume that you are not proceeding once an error occurs. – a3.14_Infinity Mar 28 '13 at 18:53

2 Answers2

2

One way to do so is passing into your method a mutable object, such as a list, and let the method change its content.

For example, in this case you can pass an empty list of error messages. If there are no errors, the list would come back empty; otherwise, the method would insert whatever errors it finds into the list, and the caller would be able to retrieve them:

public CustomObject[] retrieve(List<ErrorObject> errors) {
    ...
}

caller:

...
List<ErrorObject> errors = new ArrayList<ErrorObject>();
CustomObject[] results = wrapper.retrieve(errors);
if (results == null) {
    for (ErrorObject eo : errors) {
        ...
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You could define a global variable within the class.

private String errorMessage;

and within the class you would define your Java method.

public Object[] returnObjects {
    // code goes here
    errorMessage = "Some message";
}

In Java, it's better to return an empty array than to return null. On encountering an empty array, you would check errorMessage for the message.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • If you're going to take this approach, I would _definitely_ return `null` on error. An empty array would indicate a valid return of zero results. On return of a `null` you would check the error variable. You're object would have a public `getError` method and it would probably help to have a `isError` and maybe a `resetError` method, depending on usage. – Charles Forsythe Mar 28 '13 at 19:03