SteveSt
SteveSt

Reputation: 1297

How to read an Array variable in Java

Hello I have the following issue

I have the following function signature :

public void doSomething(Object arg);

I call this function with the following code segment :

doSomething(new Object[] {this,"aString"});

In the doSomething method implementation how can I read the data (Class Name and String) that I sent when I called it ?

Upvotes: 0

Views: 103

Answers (5)

Nikhil Talreja
Nikhil Talreja

Reputation: 2774

   public static void doSomething(Object arg) {

    if (arg instanceof Object[]) {
        Object[] list = (Object[]) arg;
        for (Object item : list) {
            System.out.println(item);
        }
    }

   }

This assumes you will always pass an Object[] as argument.

Upvotes: 3

Mustafa sabir
Mustafa sabir

Reputation: 4360

You can do the following:-

public void doSomething(Object arg){
      Object[] arr=(Object[])arg; // cast the arg into Object[] array
      Object obj=arr[0] ;// will return the object
      String s=(String)arr[1] ;// would return string (add a down-cast to string because that string object when added to array converts to the Object type)
      System.out.println(obj+" "+s);
}

If you called it in this way

doSomething(new Object[] {this,"aString"});

Ouput would be something like this:-

Class@dce1387 aString

Upvotes: 2

gotomanners
gotomanners

Reputation: 7926

You can introspect the variable passed in using instanceOf method

arg instanceof Object[]

returns boolean.

Or check the class name of the pass variable by calling arg.getClass()

arg.getClass()

return class name as String.

Upvotes: 2

Abhinav Jayaram
Abhinav Jayaram

Reputation: 156

use
arg.getClass().getSimpleName() to get Class Name
arg.getClass() to get fully qualified Class Name
arg.toString() to read the data which converts to string.

Assuming you have overidden toString() method

Upvotes: 1

Kris Scheibe
Kris Scheibe

Reputation: 361

To check whether the passed object is actually an array use

if(obj instanceof Object[]) ...

Upvotes: 3

Related Questions