我可以在Groovy中覆盖强制转换运算符吗?

时间:2011-03-09 15:00:41

标签: groovy casting

我需要尽可能与此类似的东西:

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中有这样的东西吗?

2 个答案:

答案 0 :(得分:5)

您是否尝试覆盖Object#asType(Class)方法?

答案 1 :(得分:0)

使用强制算子(as)

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) 

有关其如何工作的更多详细信息: -

http://groovy-lang.org/operators.html#_coercion_operator