类的实例<>参数

2022-09-01 20:07:24

我正在尝试编写一个方法来返回与它作为参数获得的类匹配的所有对象:

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;
    }
}

但是,我收到一个错误:“- 不兼容的操作数类型布尔值和类<捕获#1-of ?扩展方案>”

“Actor”由我的精灵扩展,比如Bird,Hero等。例如,这个想法是在给定时间获取场景中所有鸟类的列表,以进行一些计算。

你知道这是怎么回事吗?如何测试给定对象是否是给定类的实例?


答案 1
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)));
    }
}

输出:

[I'm a frog]

编辑:使用列表的更优雅的getActors()版本:

    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]);
    }

答案 2

试试这个:

cls.isInstance(yourObject)

而不是使用运算符,只有在编译时知道该类时才能使用运算符。instanceof