metaClassを使用してクラスを拡張する場合、拡張処理をどんな風に一元管理しようかいつも迷う。
いつもやっている方法は以下のとおり。
- Extention.classというクラスを作成
- 拡張処理を記述
- 利用したいコードの先頭で拡張処理の呼び出し。
具体的に例を。
Extention.groovy
1
2
3
4
5
6
7
|
String.metaClass.define{
toFile{
def file = new File(delegate)
file?.exists()?file:null
}
}
|
Test.groovy
1
2
3
4
5
6
7
8
|
#!/usr/bin/env groovy
import Extention
Extention.main()
println "/home/genzou".toFile().parent
println "/home/dummy".toFile()
|
呼び出したい拡張処理を記述したクラスのmainメソッドを呼び出す。
使用する側のコードをもうちょっと短くするなら、以下のとおり。
Extention.groovy
1
2
3
4
5
6
7
8
9
10
11
|
class Extention{
static{
String.metaClass.define{
toFile{
def file = new File(delegate)
file?.exists()?file:null
}
}
}
}
|
Test.groovy
1
2
3
4
5
6
7
8
9
|
#!/usr/bin/env groovy
import Extention
Extention
// Class.forName("Extention") でも同じ
println "/home/genzou".toFile().parent
println "/home/dummy".toFile()
|
ほんのちょっとしか変わらないけど。いきなりクラス名を記述されてもなにがなんだかっていうのもある。
ライブラリ化した拡張を使用する場合にはどんなやり方がスマートなんだろう?