Object instanceof Object

时间:2015-04-19 12:48:31

标签: java

我想检查对象是否是对象类的实例。

public Stack<Object> getObject(int x, int y, int x2, int y2, Object type, Stats stats){
    Stack<Object> ob = new Stack<Object>();
    for(Object o : stats.map){

        if(o instanceof type.getClass()){//Not working 

            if((!((o.x < x && o.x < x2) || (o.x * o.size > x && o.x * o.size > x2)) && 
                !((o.y < y && o.y < y2) || (o.y * o.size > y && o.y * o.size > y2)))){
                ob.push(o);
            }
        }
    }
    return ob;
}

我做了一些激发其他课程的课程:

(Tree,Iron,Stone)扩展了Resouce extends Object

Person extends Object

  • 如果type.getClass()= Resource:Tree,Iron和Stone应该返回true。
  • 如果type.getClass()= Tree:Tree应该返回true,而Iron和Stone应该返回false。

2 个答案:

答案 0 :(得分:2)

您无法将instanceofClass个对象一起使用。

您可以使用以下方式进行检查:

type.getClass().isInstance(o)

答案 1 :(得分:-2)

您可以使用

if(o.getClass() instanceof type.getClass()){
相关问题