背景
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()