Groovy def l = [1, 2, 3] as BlockingQueue

前端 未结 3 1474
眼角桃花
眼角桃花 2021-01-28 01:46

If I write something like def l = [1, 2, 3] as Socket which is obviously nonsense, I get this:

org.codehaus.groovy.runtime.typehandling.GroovyCastE         


        
3条回答
  •  星月不相逢
    2021-01-28 02:03

    Using x as y is not casting, it's Coercion (see Section 8.7 of the Groovy Manual).

    Coercion does not check type safety when casting.

    Also, BlockingQueue is an interface. I'm not sure why you would cast an object as an interface.

    Try running this:

    import java.util.concurrent.LinkedBlockingQueue 
    LinkedBlockingQueue l = [1, 2, 3] as LinkedBlockingQueue
    println(l instanceof LinkedBlockingQueue)
    println(l.class)
    println(l.metaClass.methods*.name.sort().unique())
    ​
    

    You get:

    true
    class java.util.concurrent.LinkedBlockingQueue
    [add, addAll, clear, contains, containsAll, drainTo, element, equals, getClass, hashCode, isEmpty, iterator, notify, notifyAll, offer, peek, poll, put, remainingCapacity, remove, removeAll, retainAll, size, take, toArray, toString, wait]
    

    You can't have an instance of an interface, so it had no idea what you asked it to do. For instance, try running new BlockingQueue(), you can't because you can't have an instance of an interface. This is why you cannot cast an Object to be an interface.

提交回复
热议问题