instanceof在Grails中 [英] instanceof in Grails

查看:99
本文介绍了instanceof在Grails中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定类中的对象在集合中?

  class Human {...} 
class Man extends Human {...}
class妇女扩展人类{...}

def humans = Human.findAll()
humans.each(){human - >

// ??? ,如果(人的instanceof女人){printlnWoman}
}

$ b

非常感谢,

Tom

解决方案

根据你的描述,我会说你正在运行Hibernate代理对象(例如,类名是:Human _ $$ javaassist *)。解决方法是使用GORM提供的insatnceOf版本。无需急于获取或使用其他方法。

  def planet = Planet.get(1)
planet。 humans.each(){human - >
if(human.instanceOf(Man)){printlnis Man}
if(human.instanceOf(Woman)){printlnis Woman}
}

注意区别human.instanceOf(Man)而不是Man的人类instanceof。使用gorm方法而不是java关键字。

您可以在[参考资料]中找到[解释] [1]的这部分内容。请参阅懒惰单端关联和代理小节



[1]: http://grails.org/doc/latest/guide/single.html#5.5.2.8 渴望和懒惰获取


How to determine Class type of Object in collection?

class Human{...}
class Man extends Human{...}
class Women extends Human{...}

def humans = Human.findAll() 
humans.each(){ human ->

    // ??? , it is not work
   if ( human instanceof Man ) { println "Man" }
   if ( human instanceof Woman ) { println "Woman" }
}

Thanks a lot,
Tom

解决方案

Based on your description, I would say you are running into Hibernate proxy objects (ie. class name is: Human_$$javaassist*). Solution would be to use the GORM provided version of insatnceOf. No need to eager fetch or use a different method.

def planet = Planet.get(1)
planet.humans.each(){ human ->
    if (human.instanceOf(Man)) { println "is Man"}
    if (human.instanceOf(Woman)) { println "is Woman"}
}

Notice the difference human.instanceOf(Man) rather than human instanceof Man. Use the gorm method rather than the java keyword.

You can see this section of the reference documentation for an [explanation][1]. See subsection "Lazy Single-Ended Associations and Proxies"

[1]: http://grails.org/doc/latest/guide/single.html#5.5.2.8 Eager and Lazy Fetching

这篇关于instanceof在Grails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆