Lena Bru
Lena Bru

Reputation: 13947

Checking if a certain object in the list is this kind of class

I want to check if an object in the list is a certain type of class

i want my method to be something like

public <T> MyCustomObject get (Class<T>clz){
List<SomeObject> list= getList();

for(SomeObject o : list){

   if o is the same class as clz, or o is a child of clz return it
}


}

and call the method like this

MyCustomObject o =  get(MyCustomObjectVeryFarDescendant.class);

what would my comparison clause look like ?

Upvotes: 1

Views: 106

Answers (3)

rachana
rachana

Reputation: 3414

This operator is used only for checking "object reference variables". This operator checks the type of "object reference variable " and return "true" if it is of the provided type.

if (objectReference instanceof type)

In this syntax, "objectReference" is the object name and "type" is the name of object type for checking it's type. The operator checks whether the object is of a particular type(class type or interface type).

For Example :

Car c = new Car();
boolean result = c instanceof Car;

This will return 'true' and store 'true' to boolean variable 'result'

To know more about instanceOf operator refer

What is instanceof operator

also

instanceof operator

Upvotes: 0

Mureinik
Mureinik

Reputation: 311188

I think that isInstance(Object) is what you're looking for:

public <T> MyCustomObject get (Class<T>clz){
   List<SomeObjects> list= getList();

   for(SomeObject o : list){
      if (clz.isInstance(o)) {
          return (T) o;
      }
   }
}

Upvotes: 3

Aniket Thakur
Aniket Thakur

Reputation: 68915

you can simply do

if(o instanceof MyCustomObjectVeryFarDescendant){
   return o;
}

It will return o if o is an instance of MyCustomObjectVeryFarDescendant or any of it's subclass.

Upvotes: -1

Related Questions