Comprobación de cadenas y una matriz de cadenas en Java

I am stuck with an issue . I am calling a method A() . Which sometimes return String and sometimes it returns Array of Strings (String[] strArr) . How can I handle that scenario programmatically ? I don't have any control in the return type of the method A() .

I have to call that method and store the returned value in a variable. The type of the variable needs to be fixed depending upon the returned value (String / Array of Strings) from the method .

Gracias de antemano.

preguntado el 28 de agosto de 12 a las 09:08

What is the signature of A()? -

What is the signature of this method? -

Puedes usar instanceof operador. -

What is the return type of A() ? How one method will allow two return types? -

I guess that the return type is Object : private Object getValue() { return condition() ? "" : new String[]{ "" }; } -

2 Respuestas

prueba este

Object returnedValue = A();
if (returnedValue instanceof String)
{
    ...
}
else if (returnedValue instanceof String[])
{
    ...
}

Respondido 28 ago 12, 09:08

This is what I was expecting for .. Thanks - Sabya

I would rather suggest change in signature of A(). The method A() should always return String[] and at the calling end check for the length of the array and perform necessary action.

Respondido 28 ago 12, 10:08

I agree with you. An API should be clear, the user should not have to cast the result. - gontardo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.