Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对象实例_Java - Fatal编程技术网

Java 对象实例

Java 对象实例,java,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 worki

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

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;
}
publicstackgetobject(intx,inty,intx2,inty2,对象类型,Stats){
Stack ob=新堆栈();
for(对象o:stats.map){
如果(o instanceof type.getClass()){//不工作
如果(!((o.xx&&o.x*o.size>x2))&&
!((o.yy&&o.y*o.size>y2))){
ob.push(o);
}
}
}
返回ob;
}
我做了一些课程,这些课程超越了其他课程:

(树、铁、石)延伸资源延伸对象

人扩展对象

  • 如果type.getClass()=Resource:Tree,Iron and Stone应该返回true
  • 如果type.getClass()=Tree:Tree应该返回true,而Iron and Stone应该返回false
您可以使用

if(o.getClass() instanceof type.getClass()){

不能将
instanceof
Class
对象一起使用

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

type.getClass().isInstance(o)

我自己,我会尝试重新设计我的代码,这样就不需要这个乱七八糟的代码实例。也许您想使用访问者设计模式(不确定)。不,我们不能有
instanceof type.getClass()
。请在发布之前测试您的答案。这不是一场竞赛(正如许多人所认为的那样)。