Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created December 9, 2012 17:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumokmm/4246193 to your computer and use it in GitHub Desktop.
Save fumokmm/4246193 to your computer and use it in GitHub Desktop.
動的プロパティ読み込みクラス in Groovy
plus={ a, b -> a + b }
minus={ a, b -> a - b }
multiply={ a, b -> a * b }
div={ a, b -> a / b }
/** 動的プロパティクラス */
class DynamicProps {
/** コンストラクタ */
DynamicProps() {
// "${このクラスの名前}.properties" という形式の
// プロパティファイルを読み込む
def prop = new File("${this.class.name}.properties")
.withReader { r ->
new Properties().with { p ->
p.load(r); p
}
}
// 動的メソッド追加!
prop.each { k, v -> initialize(k, v) }
}
/** 実装はサブクラスで */
def initialize(k, v) {
// Please override at subclass.
}
}
/** 文字列のプロパティ */
class StringProps extends DynamicProps {
@Override
def initialize(k, v) {
def methodName = "get${(k as String).capitalize()}"
this.metaClass[methodName] = { -> v }
println "${methodName} defined in class ${this.class.name}."
}
}
/** クロージャのプロパティ */
class ClosureProps extends DynamicProps {
@Override
def initialize(k, v) {
def methodName = "get${(k as String).capitalize()}"
this.metaClass[methodName] = { -> Eval.me(v) }
println "${methodName} defined in class ${this.class.name}."
}
}
/** Fumo.properties読み込みクラス */
class Fumo extends StringProps {}
def fumo = new Fumo()
assert fumo.name == 'fumokmm'
assert fumo.occupation == 'System Engineer'
/** CalcOperator.properties読み込みクラス */
class CalcOperator extends ClosureProps {}
def op = new CalcOperator()
assert op.plus(1, 2) == 3
assert (1..5).inject(op.multiply) == 120
name=fumokmm
occupation=System Engineer
$ groovy -v
Groovy Version: 2.0.5 JVM: 1.7.0_05 Vendor: Oracle Corporation OS: Mac OS X
$ groovy dynamicPropertiesTest.groovy
getName defined in class Fumo.
getOccupation defined in class Fumo.
getMultiply defined in class CalcOperator.
getMinus defined in class CalcOperator.
getDiv defined in class CalcOperator.
getPlus defined in class CalcOperator.
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment