问题描述
如果我将类似 def l = [1、2、3]的内容写为Socket
显然是胡说八道,我会得到:
If I write something like def l = [1, 2, 3] as Socket
which is obviously nonsense, I get this:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[1, 2, 3]' with class 'java.util.ArrayList' to class 'java.net.Socket'
那很有道理.
现在,我尝试一些不太冒险的事情:
Now I try something less adventurous:
import java.util.concurrent.BlockingQueue
def l = [1, 2, 3] as BlockingQueue
println l.class
println l
这不会引发异常,并显示以下内容:
This doesn't throw an exception, and prints the following:
class ArrayList1_groovyProxy
[1, 2, 3]
那么 ArrayList1_groovyProxy
是什么,为什么我可以将列表无误地投射到 BlockingQueue
,尽管它失败了( l
不会最终不会成为 BlockingQueue
实例)?
So what's ArrayList1_groovyProxy
, and why am I able to cast the list to BlockingQueue
without error despite the fact that it fails (l
doesn't end up being an BlockingQueue
instance)?
- 首先,我想指出
def l = [1、2、3],因为List
运作良好,并生成了ArrayList
尽管List
和BlockingQueue
都是接口. -
第二,在Dónal的答案之后,我尝试了以下操作:
- First of all, I'd like to point out that
def l = [1, 2, 3] as List
works well, and produces a regualr instance ofArrayList
despite the fact that bothList
andBlockingQueue
are interfaces. Second, after Dónal's answer, I tried the following:
def l = [1, 2, 3] as BlockingQueue
assert l instanceof BlockingQueue
println l.class
println l
这打印了以下几行,没有抛出断言异常:
This printed the following lines and no assertion exceptions were thrown:
class ArrayList1_groovyProxy
[1, 2, 3]
但是,此行的确抛出 MissingMethodException
:
l.offer(5)
所以断言以某种方式成功了,但是尝试将 l
用作BlockingQueue会引发异常.
So the assertion somehow succeeds, but trying to use l
as a BlockingQueue throws an exception.
第三,如果我尝试 def l = [1、2、3]作为Map
,也会发生同样的情况这段代码:
Third, the same happens if I try def l = [1, 2, 3] as Map
This code:
def l = [1, 2, 3] as Map
assert l instanceof Map
println l
println l.getClass()
不产生任何错误并打印:
produces no errors and prints:
[1, 2, 3]
class ArrayList1_groovyProxy
推荐答案
这只是Groovy可爱.可以看到您正在尝试创建一个集合,但是无法弄清楚如何构造一个BlockingQueue.它回退到代理的ArrayList.如果您在左侧使用类型声明而不是"def",那么它将被炸毁.再次,它变得很可爱,因为您使用的是def.烦人,不是吗?:)
It's just Groovy being cute. It's able to see that you're trying to create a collection, but it can't figure out how to construct a BlockingQueue. It's falling back to a proxied ArrayList. If you'd gone with a type declaration on the left side instead of a "def," it would have blown up. Again, it's getting cute because you're using a def. Annoying, isn't it? :)
这篇关于Groovy def l = [1、2、3]作为BlockingQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!