사용자 도구

사이트 도구


groovy:meta_programming

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
다음 판 양쪽 다음 판
groovy:meta_programming [2016/08/28 14:15]
kwon37xi
groovy:meta_programming [2016/08/30 08:37]
kwon37xi
줄 24: 줄 24:
   * [[http://docs.groovy-lang.org/latest/html/api/groovy/lang/ExpandoMetaClass.html|ExpandoMetaClass]] : Groovy Meta Programming의 핵심 클래스   * [[http://docs.groovy-lang.org/latest/html/api/groovy/lang/ExpandoMetaClass.html|ExpandoMetaClass]] : Groovy Meta Programming의 핵심 클래스
 <code groovy> <code groovy>
-// 아래 invokeMethod 를 구현해야 metaClass 구현체가 ExpandoMetaClass로 변경됨.+// 아래처럼 metaClass에 메소드를 추가야 metaClass 구현체가 ExpandoMetaClass로 변경됨.
 Integer.metaClass.invokeMethod = { String name, args -> /* */ } Integer.metaClass.invokeMethod = { String name, args -> /* */ }
 println Integer.metaClass.getClass().name // ExpandoMetaClass println Integer.metaClass.getClass().name // ExpandoMetaClass
 +</code>
 +
 +==== 대량의 메소드 추가 기법 ====
 +<code groovy>
 +Integer.metaClass {
 +    daysFromNow = { ->
 +        Calendar today = Calendar.instance
 +        today.add(Calendar.DAY_OF_MONTH, delegate)
 +        today.time
 +    }
 +
 +    getDaysFromNow = { ->
 +        Calendar today = Calendar.instance
 +        today.add(Calendar.DAY_OF_MONTH, delegate)
 +        today.time
 +    }
 +
 +    // static method 추가
 +    'static' {
 +        isEven = { val -> val % 2 == 0 }
 +    }
 +
 +    // 생성자 추가
 +    constructor = { Calendar calendar ->
 +        new Integer(calendar.get(Calendar.DAY_OF_YEAR))
 +    }
 +
 +    constructor = { int val ->
 +        println "Intercepting constructor call"
 +        constructor = Integer.class.getConstructor(Integer.TYPE)
 +        constructor.newInstance(val)
 +    }
 +}
 </code> </code>
  
groovy/meta_programming.txt · 마지막으로 수정됨: 2016/08/30 08:37 저자 kwon37xi