我可以在Groovy中重写cast操作符吗?
我需要尽可能类似的东西:我可以在Groovy中重写cast操作符吗?,groovy,casting,Groovy,Casting,我需要尽可能类似的东西: interface Bar { def doSomething() } class Foo { // does not implement Bar. def doSomethingElse() { } Bar asBar() { // cast overload return new Bar() { def doSomething() { doSomethin
interface Bar {
def doSomething()
}
class Foo { // does not implement Bar.
def doSomethingElse() {
}
Bar asBar() { // cast overload
return new Bar() {
def doSomething() {
doSomethingElse()
}
}
}
}
Foo foo = new Foo()
Bar bar = foo as Bar
bar.doSomething()
Groovy中是否有类似的情况?您尝试过重写方法吗?使用强制操作符(as)
有关此操作的更多详细信息,请参见:
谢谢。这一点应该放在首位。这将阻止像我这样的新手提出这样的问题。@fernacolo这是一个维基,所以你可以这样做:-)这里简单地(非常简单地)提到了它,所以我想这就是它可以扩展的地方。。。
class Identifiable {
String name
}
class User {
Long id
String name
def asType(Class target) {
if (target==Identifiable) {
return new Identifiable(name: name)
}
throw new ClassCastException("User cannot be coerced into $target")
}
}
def u = new User(name: 'Xavier')
def p = u as Identifiable
assert p instanceof Identifiable
assert !(p instanceof User)