instanceof Class <! - ? - >参数

时间:2012-11-09 12:29:09

标签: java instanceof

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

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

然而,我收到一个错误:“ - 不兼容的操作数类型boolean和Class

鸟,英雄等等,我的精灵们扩展了'演员'。 例如,想法是在给定时间获得场景中所有鸟类的列表以进行某些计算。

知道这里发生了什么吗?如何测试给定对象是否是给定类的实例?

3 个答案:

答案 0 :(得分:30)

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]

编辑:使用List:

更优雅的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]);
    }

答案 1 :(得分:6)

试试这个:

cls.isInstance(yourObject)

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

答案 2 :(得分:3)

instanceof只能与类文字一起使用。您需要使用Class.isInstance(),即

if (cls.isInstance(actors[k]))