2011-03-09 86 views
3

我需要儘可能相似的內容:我可以在Groovy中覆蓋cast操作符嗎?

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?

回答

4

您是否嘗試過重寫Object#asType(Class)方法?

+0

謝謝。這應該放在http://groovy.codehaus.org/Operator+Overloading上。它會阻止像我這樣的新手提出這樣的問題。 – fernacolo 2011-03-09 15:11:22

+2

@fernacolo它是一個wiki,所以你可以做到這一點:-) – 2011-03-09 17:00:07

+0

這裏簡要地(很簡短)在這裏提到http://groovy.codehaus.org/Operators#Operators-ObjectRelatedOperators所以我想這就是它可以做擴展... – 2011-03-10 15:19:59

0

使用強制運營商(如)

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