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

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

问题描述

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

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.

如果这是正确的,那么当您声明类型时呢?java虚拟机是否仍然因为原始代码是groovy而最终使用反射?还是我一开始对这件事的理解是错误的?

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?

推荐答案

似乎类型声明对 Groovy 调用方法的方式没有任何特定影响.本质上,正如 在 Groovy wiki 中所述,Groovy 不会简单地调用该方法,而是会调用invokeMethod() 在对象的元类上,它要么委托给元类中定义的方法,要么执行该方法的反射查找.

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.

值得注意的是,元类使用了MetaMethod,在最坏的情况下,它使用缓存反射查找,即它只需要进行一次反射查找.

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.

编辑

使用 groovypp 可以避免部分开销,它为Groovy 代码.

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

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

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