Groovy - 扩展结构

Groovy - extensions structure

我想扩展 StringasType 方法来处理 LocalDateTime。我知道如何覆盖此方法,但是我不知道应该将它放在项目结构中的什么位置才能在全球范围内工作——对于我项目中的所有字符串。将这样的 extension 放在类路径中的任何地方就足够了吗?我知道有一个特殊的扩展约定 (META-INF/services),它如何用于方法覆盖?

可以找到关于该主题的所有文档here. And here可以找到完全相关的部分。

模块扩展和模块描述符

For Groovy to be able to load your extension methods, you must declare your extension helper classes. You must create a file named org.codehaus.groovy.runtime.ExtensionModule into the META-INF/services directory:

org.codehaus.groovy.runtime.ExtensionModule moduleName=Test module for specifications moduleVersion=1.0-test extensionClasses=support.MaxRetriesExtension staticExtensionClasses=support.StaticStringExtension The module descriptor requires 4 keys:

moduleName : the name of your module

moduleVersion: the version of your module. Note that version number is only used to check that you don’t load the same module in two different versions.

extensionClasses: the list of extension helper classes for instance methods. You can provide several classes, given that they are comma separated.

staticExtensionClasses: the list of extension helper classes for static methods. You can provide several classes, given that they are comma separated.

Note that it is not required for a module to define both static helpers and instance helpers, and that you may add several classes to a single module. You can also extend different classes in a single module without problem. It is even possible to use different classes in a single extension class, but it is recommended to group extension methods into classes by feature set.

模块扩展和类路径

It’s worth noting that you can’t use an extension which is compiled at the same time as code using it. That means that to use an extension, it has to be available on classpath, as compiled classes, before the code using it gets compiled. Usually, this means that you can’t have the test classes in the same source unit as the extension class itself. Since in general, test sources are separated from normal sources and executed in another step of the build, this is not an issue.