AbstractSyntheticMetaMethods.groovy
01 /*
02  * Copyright 2007-2012 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package griffon.app
17 
18 /**
19  @author Danno Ferrin
20  @author Andres Almiray
21  */
22 class AbstractSyntheticMetaMethods {
23     private static final String ENHANCED = "_ENHANCED_METACLASS_"
24 
25     static boolean hasBeenEnhanced(Class klass) {
26         MetaClassRegistry mcr = GroovySystem.metaClassRegistry
27         MetaClass mc = mcr.getMetaClass(klass)
28         if (!(mc instanceof ExpandoMetaClass)) return false
29         return mc.hasMetaProperty(ENHANCED)
30     }
31 
32     static void enhance(Class klass, Map enhancedMethods) {
33         MetaClassRegistry mcr = GroovySystem.metaClassRegistry
34         MetaClass mc = mcr.getMetaClass(klass)
35         boolean init = false
36         if (!(mc instanceof ExpandoMetaClass||
37                 (mc instanceof ExpandoMetaClass && !mc.isModified())) {
38             mcr.removeMetaClass klass
39             mc = new ExpandoMetaClass(klass)
40             init = true
41         }
42         // if mc is an EMC that was initialized previously
43         // with additional methods/properties and it does
44         // not allow modifications after init, then the next
45         // block will throw an exception
46         enhancedMethods.each {k, v ->
47             if (mc.getMetaMethod(k== null) {
48                 mc.registerInstanceMethod(k, v)
49             }
50         }
51         mc.registerBeanProperty(ENHANCED, true)
52         if (init) {
53             mc.initialize()
54             mcr.setMetaClass(klass, mc)
55         }
56     }
57 }