前言
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