我是靠谱客的博主 跳跃蜻蜓,这篇文章主要介绍【Groovy】Groovy 动态语言特性 ( Groovy 中函数实参自动类型推断 | 函数动态参数注意事项 )前言一、Groovy 中函数实参自动类型推断二、函数动态参数注意事项三、完整代码示例,现在分享给大家,希望可以做个参考。

文章目录

  • 前言
  • 一、Groovy 中函数实参自动类型推断
  • 二、函数动态参数注意事项
  • 三、完整代码示例

前言

Groovy 是动态语言 , Java 是静态语言 ;

本篇博客讨论 Groovy 中 , 函数实参的自动类型推断 ;





一、Groovy 中函数实参自动类型推断



定义两个不同的类 Student 和 Worker , 在类中都定义 hello 方法 ;

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
class Student { def hello(){ println "Hello Student" } } class Worker { def hello(){ println "Hello Worker" } }

声明一个方法 , 接收参数 object , 暂不指定参数类型 , 在函数中调用参数对象的 hello 方法 ;

复制代码
1
2
3
4
void fun(object) { object.hello() }

分别向该 fun 函数中传入 Student 和 Worker 对象 , 则会分别调用对应类中的 hello 方法 ;

复制代码
1
2
3
fun(new Student()) fun(new Worker())




二、函数动态参数注意事项



这里要特别注意 , 不要传递错误的对象 , 如果类中没有定义 hello 方法 , 编译时可以编译通过 , 但是运行时会报错 ;

如 : 定义了一个没有 hello 方法的类 ,

复制代码
1
2
class Farmer {}

该该类实例对象传入 fun 方法作为参数 ,

复制代码
1
2
fun(new Farmer())

就会报如下错误 :

复制代码
1
2
3
4
5
6
7
8
9
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 语言的动态性 ;

复制代码
1
2
3
4
5
@TypeChecked void fun(Student object) { object.hello() }




三、完整代码示例



完整代码示例 :

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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())

执行结果 :

复制代码
1
2
3
Hello Student Hello Worker

在这里插入图片描述

最后

以上就是跳跃蜻蜓最近收集整理的关于【Groovy】Groovy 动态语言特性 ( Groovy 中函数实参自动类型推断 | 函数动态参数注意事项 )前言一、Groovy 中函数实参自动类型推断二、函数动态参数注意事项三、完整代码示例的全部内容,更多相关【Groovy】Groovy内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部