Groovy – 扩展结构

我想扩展String的asType方法来处理LocalDateTime.我知道如何覆盖这个方法,但是我不知道我应该把它放在项目结构中以便全局工作 – 对于我项目中的所有字符串.是否足以将此类扩展放在类路径中的任何位置?我知道有一个特殊的扩展约定(META-INF / services),它如何用于方法覆盖? 最佳答案 有关此主题的所有文档都可以在
here找到.而
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.

点赞