9
저는 Groovy에서 메타 클래스 프로그래밍을하고 있습니다. 그러나 갑자기 난 그냥 작동되지 수있는 작은 문제 ... 여기 메타 클래스에 메서드 추가
는 간단한 스크립트입니다 직면했다 :// define simple closure
def printValueClosure = {
println "The value is: '$delegate'"
}
String.metaClass.printValueClosure = printValueClosure
// works fine
'variable A'.printValueClosure()
// define as method
def printValueMethod(String s){
println "The value is: '$s'"
}
// how to do this!?
String.metaClass.printValueMethod = this.&printValueMethod(delegate)
'variable B'.printValueMethod()
가이 방법을 사용할 수를하지만, 호출에 첫 번째 매개 변수를 설정 목적? 대리자를 사용하여 작동하지 않는 것 같습니다 ... 호출자를 참조하지 않는 메서드를 할당해도 아무런 문제가 없습니다. 여기서 카레가 작동합니까?
def printValueMethod(String s){
println "The value is: '$s'"
}
String.metaClass.printValueMethod = { -> printValueMethod(delegate) }
assert 'variable B'.printValueMethod() == "The value is: 'variable B'"
숙어 방법을하는 것 클로저를 사용하지 않고 메소드를 추가 :
감사합니다, 잉고
니스. 감사. 그것의 생각도하지 ... 클래스에 (클래스를 사용하지 않고) 많은 정적 도우미 메서드를 추가하는 편리한 방법이 있습니까? 예를 들어 Apache Commons IO FileUtils를 파일 클래스에? – Ingo
아 ... 편집 내용도 내 추가 질문에 대한 답변입니다. 다시 한번 감사드립니다. – Ingo