Declaring Types in Groovy

前端 未结 5 1700
天命终不由人
天命终不由人 2020-12-19 07:31

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 obje

5条回答
  •  鱼传尺愫
    2020-12-19 08:05

    It still makes heavy use of reflection.
    One of the things you must have in mind, is that the methods calls are resolved at runtime.
    Easiest way to see it

    Integer.metaClass.xxx << {println "hi"}
    Integer ten = 10
    ten.xxx()
    

    This compiles, even though a normal Integer 100 would not have method xxx.
    The first line adds the method to the class, but the compiler would not know this at compile time (the method is added at runtime).
    It does not matter that the type is known, groovy still uses reflection to perform the calls.
    Another example.

    def (Number i, Number l) = [100, 100L]
    print i
    print l
    def print(Number n)  {println "Number $n"}
    def print(Integer n) {println "Integer $n"}
    

    In java, it would print Number 100 twice, as the method is statically selected.
    Groovy doesn't care and just selects the method based on the class of the arguments at runtime.

提交回复
热议问题