Reputation: 3028
In Java i want to find whether object is a object collection??
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
I want to check varaible ob holds object collection??How can i do this??
Upvotes: 2
Views: 271
Reputation: 3863
First check is it an array with:
boolean isArray = ob.getClass().isArray();
or
if (ob instanceof Object[]) {
// ...
}
If not check is it an collection by checking with instanceof and java.util.Collection
interface:
if (ob instanceof Collection) {
// ...
}
Upvotes: 0
Reputation: 41240
check with instanceof
operator.
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that >implements a particular interface. reference
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
...
if(ob instanceof String[]){
String[] str = (String[])ob;
}else{...}
Upvotes: 1
Reputation: 40076
From your example, what you need to check is more precisely, Object Array instead of collection.
You can try something like
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
if (ob instanceof Object[]) {
// do something
}
Upvotes: 0
Reputation: 2132
You can use Java reflections, like this:
Class<?> clazz = ob.getClass();
boolean isArray = clazz.isArray();
Upvotes: 2