我有一个名为 Video 的类和这个类的一个对象(这里称为“b”)
这是测试用例:
log.debug b
log.debug b.class
log.debug (b.class == Video)
log.debug (b instanceof Video)
log.debug (b.instanceOf(Video))
log.debug (b in Video)
输出是:
DEBUG NavLinkHelperTagLib - product.content.Video : 4352
DEBUG NavLinkHelperTagLib - class product.content.Video
DEBUG NavLinkHelperTagLib - true
DEBUG NavLinkHelperTagLib - false
DEBUG NavLinkHelperTagLib - true
DEBUG NavLinkHelperTagLib - false
有人能告诉我为什么 instanceof 会失败吗?!
编辑:
我感觉这与 GORM 相关。这是我的类(class):
abstract class Product implements Serializable {
static hasMany = [additionalContents:AdditionalContent]
}
abstract class AdditionalContent implements Serializable{
static belongsTo = [product:Product]
}
class Video extends AdditionalContent {
}
我认为这里的问题是延迟加载?但是当这是代理/惰性问题时,通常我会在调用 .getClass() 时看到类似 Video$$javaassist 的内容,但我没有看到这个...
最佳答案
这是 Hibernate/Gorm 相关的。您的域对象很可能由 Hibernate 代理。因此,您不能使用 Java instanceOf
。
Grails 团队意识到了这个问题,因此他们在每个 Grails 域对象上引入了 instanceOf()
方法。以下引述来自 Grails reference .
You can protect yourself to a degree from this problem by using the instanceOf method by GORM:
def person = Person.get(1)
assert Pet.list()[0].instanceOf(Dog)
因此只能使用instanceOf()
方法比较域类。
为了查看instanceOf
是如何实现的,您需要使用JD-GUI 反编译您的Video
域类。 .
在 Grails 3 应用程序中,这是由特征 GormEntity
实现的。
@Traits.TraitBridge(traitClass=GormEntity.class, desc="(Ljava/lang/Class;)Z")
public boolean instanceOf(Class arg1)
{
// Byte code:
// 0: invokestatic 88 ch/silviowangler/zscsupporter/Game:$getCallSiteArray ()[Lorg/codehaus/groovy/runtime/callsite/CallSite;
// 3: astore_2
// 4: aload_2
// 5: ldc_w 548
// 8: aaload
// 9: ldc -104
// 11: aload_0
// 12: aload_1
// 13: invokeinterface 209 4 0
// 18: invokestatic 182 org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation:booleanUnbox (Ljava/lang/Object;)Z
// 21: ireturn
// 22: nop
// 23: nop
// 24: nop
// 25: nop
// 26: nop
// 27: nop
// 28: nop
// 29: nop
// 30: athrow
// Local variable table:
// start length slot name signature
// 0 22 0 this Game
// 0 22 1 arg1 Class
}
这是了解 instanceOf
方法行为方式的唯一方法。
关于java/groovy/grails instanceof 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35896648/