0

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 ?

1
  • 1
    If you alway pass Object[] (as you mentioned in one of your comments) change the method signature to `public void doSomething(Object[] arg). Commented Jun 20, 2014 at 8:22

5 Answers 5

3
   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.

Sign up to request clarification or add additional context in comments.

3 Comments

I always do that, but is there any way to check that I pass an Object[] as argument ?
if(arg != null && arg.getClass().isArray()) { ... }
I think Kris answered that for you @SteveSt. Can you mark this as the correct answer if it works for you?
3

To check whether the passed object is actually an array use

if(obj instanceof Object[]) ...

Comments

2

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.

Comments

2

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

Comments

1

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

1 Comment

assuming arg is an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.