文章目錄
- 前言
- 一、Groovy 中函式實參自動型別推斷
- 二、函式動態引數注意事項
- 三、完整代碼示例
前言
Groovy 是動態語言 , Java 是靜態語言 ;
本篇博客討論 Groovy 中 , 函式實參的自動型別推斷 ;
一、Groovy 中函式實參自動型別推斷
定義兩個不同的類 Student 和 Worker , 在類中都定義 hello 方法 ;
class Student {
def hello(){
println "Hello Student"
}
}
class Worker {
def hello(){
println "Hello Worker"
}
}
宣告一個方法 , 接收引數 object , 暫不指定引數型別 , 在函式中呼叫引數物件的 hello 方法 ;
void fun(object) {
object.hello()
}
分別向該 fun 函式中傳入 Student 和 Worker 物件 , 則會分別呼叫對應類中的 hello 方法 ;
fun(new Student())
fun(new Worker())
二、函式動態引數注意事項
這里要特別注意 , 不要傳遞錯誤的物件 , 如果類中沒有定義 hello 方法 , 編譯時可以編譯通過 , 但是運行時會報錯 ;
如 : 定義了一個沒有 hello 方法的類 ,
class Farmer {}
該該類實體物件傳入 fun 方法作為引數 ,
fun(new Farmer())
就會報如下錯誤 :
Caught: groovy.lang.MissingMethodException: No signature of method: Farmer.hello() is applicable for argument types: () values: []
Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), getAt(java.lang.String), each(groovy.lang.Closure), split(groovy.lang.Closure), wait()
groovy.lang.MissingMethodException: No signature of method: Farmer.hello() is applicable for argument types: () values: []
Possible solutions: sleep(long), sleep(long, groovy.lang.Closure), getAt(java.lang.String), each(groovy.lang.Closure), split(groovy.lang.Closure), wait()
at Worker$hello.call(Unknown Source)
at Groovy.fun(Groovy.groovy:17)
at Groovy$fun.callCurrent(Unknown Source)
at Groovy.run(Groovy.groovy:22)
為了避免上述問題 , 可以在函式上使用 @TypeChecked 注解 , 但是相應的 , 也就失去了 Groovy 語言的動態性 ;
@TypeChecked
void fun(Student object) {
object.hello()
}
三、完整代碼示例
完整代碼示例 :
class Student {
def hello(){
println "Hello Student"
}
}
class Worker {
def hello(){
println "Hello Worker"
}
}
class Farmer {}
void fun(object) {
object.hello()
}
fun(new Student())
fun(new Worker())
// 下面的用法會報 Caught: groovy.lang.MissingMethodException 例外
//fun(new Farmer())
執行結果 :
Hello Student
Hello Worker

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413488.html
標籤:其他
上一篇:GNUstep
下一篇:【Groovy】Groovy 動態語言特性 ( Groovy 語言與 Java 語言執行效率對比 | 以動態特性編譯的 Groovy 類 | 以靜態特性編譯的 Groovy 類 )
