运行时掺元
现在来介绍今天的最后一个元编程特性:运行时掺元。凭借@Mixin,你可以将新的行为混合到你所拥有的类中。但是你不能给无法拥有的类混入任何东西。运行时掺元旨在运行时向任意类型中添加掺元来解决这个问题。回想一下之前混入了能力的vehicle示例,如果我们无法拥有James Bond的vehicle却想为其增加潜水功能,可以这么做:
1 // provided by a third-party
2
3 interface Vehicle {
4
5 String getName()
6
7 }
8
9 // provided by a third-party
10
11 class JamesBondVehicle implements Vehicle {
12
13 String getName() { "James Bond's vehicle" }
14
15 }
16
17 JamesBondVehicle.mixin DivingAbility, FlyingAbility
18
19 assert new JamesBondVehicle().fly() ==
20
21 "I'm the James Bond's vehicle and I fly!"
22
23 assert new JamesBondVehicle().dive() ==
24
25 "I'm the James Bond's vehicle and I dive!"
2
3 interface Vehicle {
4
5 String getName()
6
7 }
8
9 // provided by a third-party
10
11 class JamesBondVehicle implements Vehicle {
12
13 String getName() { "James Bond's vehicle" }
14
15 }
16
17 JamesBondVehicle.mixin DivingAbility, FlyingAbility
18
19 assert new JamesBondVehicle().fly() ==
20
21 "I'm the James Bond's vehicle and I fly!"
22
23 assert new JamesBondVehicle().dive() ==
24
25 "I'm the James Bond's vehicle and I dive!"
我们可以将一个或多个掺元以参数的形式传到静态的mixin()方法中(该方法由Groovy在Class上添加)来实现。