Khoi
Khoi

Reputation: 4635

convert Object into Object[]

the method inside the library I'm using return an object but it's really is an array of objects. And I'm stuck where I need that value. It's weird that no one has asked for a conversion like this.

Upvotes: 5

Views: 8950

Answers (4)

Rekin
Rekin

Reputation: 9971

    Object[] objects = new Object[] {1,"fde", 5L};
    Object cast = objects;
    Object[] recovered = (Object[]) cast;

Upvotes: 9

Arjan Tijms
Arjan Tijms

Reputation: 38163

Many APIs return Object, because that's the most general thing to return. This is typically the case for general containers in which you can store many different types. A getter style method is then unable to return anything more specific.

There should be no need for any explicit 'conversion'. Just cast it and you're done.

Object object = MyApi.getFoo();
Object[] theRealThing = (Object[]) object;

Or if you want to be sure that the cast is going to work:

Object object = MyApi.getFoo();
if (object instanceof Object[]) {
    Object[] theRealThing = (Object[]) object;
} else {
    System.out.println("The impossible has happened!"); // or something like that
}

Upvotes: 3

ehsun7b
ehsun7b

Reputation: 4866

You can simplay cast it like this:

Object[] arrayOfObjects = (Object[]) yourMethod();

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038880

Object o = ...
Object[] array = { o };

Upvotes: 3

Related Questions