6

背景

Groovy 具有向现有类添加方法的功能,我发现了一些 有趣的方法。

然后我发现我需要自定义我的 Grails 引导程序来加载它们,所以我添加了:

def init = { servletContext -> addExtensionModules() }

  def addExtensionModules() {

    Map<CachedClass, List<MetaMethod>> map = [:]
    ClassLoader classLoader = Thread.currentThread().contextClassLoader
    try {
      Enumeration<URL> resources = classLoader.getResources(MetaClassRegistryImpl.MODULE_META_INF_FILE)
      for (URL url in resources) {
        if (url.path.contains('groovy-all')) {
          // already registered
          continue
        }
        Properties properties = new Properties()
        InputStream inStream
        try {
          inStream = url.openStream()
          properties.load(inStream)
          GroovySystem.metaClassRegistry.registerExtensionModuleFromProperties(properties,
                            classLoader, map)
        }
        catch (IOException e) {
          throw new GroovyRuntimeException("Unable to load module META-INF descriptor", e)
        } finally {
          inStream?.close()
        }
      }
    }  catch (IOException ignored) {}
    map.each { CachedClass cls, List<MetaMethod> methods ->
    cls.setNewMopMethods(methods)
  }
}

我添加了我的 BuildConfig.groovy

compile ('ca.redtoad:groovy-crypto-extensions:0.2') {
  excludes 'groovy-all'
}

问题

问题是现在我不能使用toBoolean()Groovy String 的方法:

groovy.lang.MissingMethodException:没有方法签名:java.lang.String.toBoolean() 适用于参数类型:() 值:[] 可能的解决方案:asBoolean()、asBoolean()、toFloat()、toDouble()

既然 groovy 已经注册了,为什么缺少这个方法呢?我正在使用 Grails 2.2.4。

编辑

在 groovy 2.0.8 控制台中测试,代码有效,所以可能与 Grails 相关。

@Grab('ca.redtoad:groovy-crypto-extensions:0.2')
@GrabExclude('org.codehaus.groovy:groovy-all')

addExtensionModules() //same method of BootStrap, ommited to make shorter.

def key = "password".toKey()
def ciphertext = "some plaintext".bytes.encrypt(key: key)
def x = new String(ciphertext.decrypt(key: key)).toBoolean()
println "S".toBoolean()
4

1 回答 1

6

代替

map.each { CachedClass cls, List<MetaMethod> methods ->
    cls.setNewMopMethods(methods)
}

map.each { CachedClass cls, List<MetaMethod> methods ->
    //Add new MOP methods instead of set them as new
    cls.addNewMopMethods(methods) 
}

当在CachedClass现有扩展/元方法中设置新的元方法时,扩展模块中唯一提供的扩展会覆盖。在这种情况下,groovy-crypto-extension在 String 类上使用以下扩展方法

class java.lang.String=
[public static javax.crypto.spec.SecretKeySpec ca.redtoad.groovy.extensions.crypto.CryptoExtensionMethods.toKey(java.lang.String), 
 public static javax.crypto.spec.SecretKeySpec ca.redtoad.groovy.extensions.crypto.CryptoExtensionMethods.toKey(java.lang.String,java.util.Map)
] 

如果这些方法设置为 CachedClass,则现有方法将被清除。所以必须将它们添加到 CachedClass 中。因此,toBoolean在 String 类上可用。

挑战接受并执行。你欠我一个款待。(礼品卡也可以接受)。;)

于 2013-10-24T15:16:51.407 回答