Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof Class<?> parameter

Tags:

I'm trying to write a method to return all objects that match the class it gets as a parameter:

public class Scenario extends View {      ...      private Actor[] actors = new Actor[1024];      ...      public Actor[] getActors(Class<?> cls) {         //Count actors corresponding to class cls         int cnt = 0;               for (int i = 0; i<actorsCount; i++)            if (actors[i] instanceof cls) cnt++;            //Build a new array;         Actor[] clsActors = new Actor[cnt];          //Fill it         for (int j = 0, k=0; j<cnt; k++)            if (actors[k] instanceof cls)               clsActors[j++] = actors[k];          return clsActors;     } } 

However, I'm getting an error: "- Incompatible operand types boolean and Class<capture#1-of ? extends Scenario>"

'Actor' is extended by my sprites, say Bird, Hero, etc. The idea is, for example, to get a list of all Birds on the Scenario at a given time for some calculations.

Any idea what's going on here? How to test if a given object is an instance of a given class?

like image 629
マルちゃん だよ Avatar asked Nov 09 '12 12:11

マルちゃん だよ


People also ask

How to check if an object is an instance of class?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns false. In the above example, we have created a variable name of the String type and an object obj of the Main class.

When to use instanceof with the object type in Java?

Using instanceof with the Object Type In Java, every class implicitly inherits from the Object class. Therefore, using the instanceof operator with the Object type will always evaluate to true: 5. Using the instanceof Operator When an Object Is null If we use the instanceof operator on any object that is null, it returns false.

What is the use of instanceof operator in C++?

The instanceof operator is also used to check whether an object of a class is also an instance of the interface implemented by the class. For example, In the above example, the Dog class implements the Animal interface. Inside the print statement, notice the expression, Here, d1 is an instance of Dog class.

What is the use of instanceof in Python?

The instanceof operator allows to check whether an object belongs to a certain class. It also takes inheritance into account. Such a check may be necessary in many cases, here we’ll use it for building a polymorphic function, the one that treats arguments differently depending on their type.


2 Answers

import java.util.Arrays;  public class Main {     static class Actor {}     static class Frog extends Actor {@Override public String toString() {return "I'm a frog";}}     static class Lizard extends Actor {@Override public String toString() {return "I'm a lizard";}}          private static Actor[] actors;                  public static Actor[] getActors(Class<?> cls) {             //Count actors corresponding to class cls             int cnt = 0;                   for (int i = 0; i<actors.length; i++)                if (cls.isInstance(actors[i])) cnt++;               //Build a new array;             Actor[] clsActors = new Actor[cnt];              //Fill it             for (int j = 0, k=0; j<cnt; k++)                     if (cls.isInstance(actors[k]))                   clsActors[j++] = actors[k];              return clsActors;         }      public static void main(String[] args)     {             actors = new Actor[] {new Frog(), new Lizard()};             System.out.println(Arrays.toString(getActors(Frog.class)));     } } 

Output:

[I'm a frog] 

Edit: More elegant version of getActors() using a List:

    public static Actor[] getActors(Class<?> cls) {         LinkedList<Actor> chosenActors = new LinkedList<Actor>();                    for(Actor actor: actors) if(cls.isInstance(actor)) chosenActors.add(actor);                                  return chosenActors.toArray(new Actor[0]);     } 
like image 55
Konrad Höffner Avatar answered Nov 12 '22 14:11

Konrad Höffner


Try this:

cls.isInstance(yourObject) 

instead of using the instanceof operator, which can only be used if you know the class at compile time.

like image 23
Costi Ciudatu Avatar answered Nov 12 '22 15:11

Costi Ciudatu