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()
。请在发布之前测试您的答案。这不是一场竞赛(正如许多人所认为的那样)。