在Groovy中声明类型 [英] Declaring Types in Groovy

查看:138
本文介绍了在Groovy中声明类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你没有在groovy中声明一个变量的类型时,我的理解是,java虚拟机必须使用反射才能确定在执行任何方法之前对象是什么类型,并且有可能抛出运行时错误。



如果这是正确的,那么当您声明类型时怎么办? java虚拟机仍然最终使用反射,因为原来的代码是在groovy?或者是我对这个问题的理解在第一个地方是不正确的?

解决方案

它不会显示为类型声明对Groovy调用方法的具体影响。基本上,正如Groovy wiki上 所述,Groovy将调用该方法,而不是简单地调用该方法对象元类的invokeMethod(),它可以委托给元类中定义的方法或者执行方法的反射查找。



值得注意的是,元类使用了 MetaMethod ,在最糟糕的情况下,它使用缓存反射查找,也就是说,它只需要进行单个反射查找。

编辑



使用可以避免一些此类开销groovypp ,它为Groovy代码添加了静态打字功能。


When you don't declare a type for a variable in groovy, it is my understanding that the java virtual machine has to use reflection in order to figure out what type the object is before executing any methods and has the potential of throwing a runtime error.

If that is correct, what about when you declare the type? Does the java virtual machine still end up using reflection because the original code was in groovy? Or is my understanding of this whole matter incorrect in the first place?

解决方案

It doesn't appear as though type declarations have any specific influence on how Groovy invokes the method. Essentially, as noted on the Groovy wiki, instead of simply invoking the method, Groovy will call invokeMethod() on the object's metaclass, which either delegates to a method defined in the metaclass or performs a reflective lookup of the method.

It's worth noting that the metaclass makes use of a MetaMethod, which, in the worst case, uses a cached reflection lookup, i.e., it only needs to make a single reflective lookup.

Edit

Some of this overhead may be avoidable by using groovypp, which adds static typing capabilities to Groovy code.

这篇关于在Groovy中声明类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆