Reputation: 1297
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
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
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
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
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
Reputation: 361
To check whether the passed object is actually an array use
if(obj instanceof Object[]) ...
Upvotes: 3