我在Grails中用继承对我的域类进行了建模,如下所示。
abstract class Profile{
}
class Team extends Profile{
}
class User extends Profile{
}
class B{
static hasMany = [profiles: Profile]
}
稍后在控制器中,当我在某些情况下从类B获得所有配置文件时,我想将一些配置文件强制转换为Team或User,但我不能,因为我获得了java.lang.ClassCastException或GroovyCastException,尽管它们被保存为Team或User(在数据库中具有属性类)。以下是我尝试过的方法:
def team1 = b.profiles.toList()[0] as Team
def team1 = (Team)b.profiles.toList()[0]
当我不写任何类型的东西时,它就起作用了,只是在动态语言中正常使用它。
def team1 = b.profiles.toList()[0]
但我永远不知道我在用哪个类。groovy或gorm中是否有将父类强制转换为子类的方法?
答案是No,因为真正的GORM/HHibernate实例是代理对象。因此,它不能直接转换为实体类。
无论如何,这可能会有所帮助:
def team1 = b.profiles.toList()[0]
if(team1.instanceOf(Team)) {
// I am an instance of Team
// do something here.
}