vmb
vmb

Reputation: 3028

How to check whether object Containing object collection

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

Answers (4)

Michał Kupisiński
Michał Kupisiński

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

Subhrajyoti Majumder
Subhrajyoti Majumder

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

Adrian Shum
Adrian Shum

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

Shivam
Shivam

Reputation: 2132

You can use Java reflections, like this:

Class<?> clazz = ob.getClass();
boolean isArray = clazz.isArray();

Upvotes: 2

Related Questions