运行时和编译时元编程—运行时元编程

原文链接   译文链接   译者:JackWang

运行时和编译时元编程 第一部分

Groovy语言支持两种风格的元编程:运行时元编程和编译时元编程。第一种元编程支持在程序运行时修改类模型和程序行为,而第二种发生在编译时。两种元编程有各自的优缺点,在这一章节我们将详细讨论。

注:译者也是第一次接触Groovy,由于时间和水平有限(姑且让译者使用这个理由吧,对待知识本应该一丝不苟)部分专有名词可能翻译不准确甚至有误(读者阅读的过程中最好能参考原文),恳请读者不吝留言指出,谢谢!

1.运行时元编程

通过运行时元编程,我们可以推迟运行时的分支决策(译者注:该处原文为we can postpone to runtime the decision,对于decision,译者也找不到一个合适的表达,请读者根据下图和上下文理解,如果读者有更好的翻译请留言指出,谢谢)来拦截,注入甚至合成类或接口的方法。对于Groovy MOP(译者注:对于初学者,这里突然冒出这个新名词,译者也头大,通过查询,MOP是Mete Object Protocol的缩写,读者可参考该文来了解)的更深理解,我们需要理解Groovy的对象和方法处理。在Groovy里,我们主要使用三种类型的对象:POJO,POGO和Groovy拦截器。Groovy支持元编程多种方式来对这些类型对象进行元编程。

  • POJO – 一个普通的Java对象,它的类可以使用Java或其他支持JVM的语言来编写。
  • POGO – 一个Groovy对象,类用Groovy实现。默认继承了java.lang.Object并且实现了groovy.lang.GroovyObject接口。
  • Groovy 拦截器 – 实现了groovy.lang.GroovyInterceptable接口并且具有方法拦截能力的Groovy对象,我们将在GroovyInterceptable这一节详细讨论。

对于每次方法调用,Groovy都会检查对象是一个POJO还是一个POGO。对于POJOs,Groovy从groovy.lang.MetaClassRegistry类中携带元信息并且委托方法来调用。对于POGOs,Groovy有更复杂的不知,我们在下图演示:

1.1 GroovyObject接口

Groovy.lang.GroovyObject的地位和Java中的Object类一样,是一个主接口。GroovyObject有一个默认的实现类groovy.lang.GroovyObjectSupport,这个类的主要职责是转换groovy.lang.MetaClass对象的调用。GroovyObject源码类似下面这样

[code]
package groovy.lang;

public interface GroovyObject {

Object invokeMethod(String name, Object args);

Object getProperty(String propertyName);

void setProperty(String propertyName, Object newValue);

MetaClass getMetaClass();

void setMetaClass(MetaClass metaClass);
}
[/code]

1.1.1 invokeMethod

根据运行时元编程的规定,当你调用的方法不是Groovy对象时将会调用这个方法。这儿有一个简单的示例演示重载invokeMethod()方法:

[code]
class SomeGroovyClass {

def invokeMethod(String name, Object args) {
return "called invokeMethod $name $args"
}

def test() {
return ‘method exists’
}
}

def someGroovyClass = new SomeGroovyClass()

assert someGroovyClass.test() == ‘method exists’
assert someGroovyClass.someMethod() == ‘called invokeMethod someMethod []’
[/code]

1.1.2 get/setProperty

通过重载当前对象的getProperty()方法可以使每次读取属性时被拦截。下面是一个简单的示例:

[code]
class SomeGroovyClass {

def property1 = ‘ha’
def field2 = ‘ho’
def field4 = ‘hu’

def getField1() {
return ‘getHa’
}

def getProperty(String name) {
if (name != ‘field3’)
return metaClass.getProperty(this, name) //(1)
else
return ‘field3’
}
}
def someGroovyClass = new SomeGroovyClass()

assert someGroovyClass.field1 == ‘getHa’
assert someGroovyClass.field2 == ‘ho’
assert someGroovyClass.field3 == ‘field3’
assert someGroovyClass.field4 == ‘hu’
[/code]

(1) 将请求的getter转到除field3之外的所有属性
你可以重载setProperty()方法来拦截写属性:

[code]
class POGO {

String property

void setProperty(String name, Object value) {
this.@"$name" = ‘overriden’
}
}

def pogo = new POGO()
pogo.property = ‘a’

assert pogo.property == ‘overriden’
[/code]

1.1.3 get/setMetaClass

你可以访问一个对象的metaClass或者通过改变默认的拦截机制来设置实现你自己的MetaClass。比如说你通过写你自己的MetaClass实现接口来将一套拦截机制分配到一个对象上:

[code]
// getMetaclass
someObject.metaClass

// setMetaClass
someObject.metaClass = new OwnMetaClassImplementation()
[/code]

你可以在GroovyInterceptable专题里找到更多的例子。

1.2 get/setAttribute

这个功能和MetaClass实现类相关。在该类默认的实现里,你可以无需调用他们的getter和setters方法来访问属性。下面是一个示例:

[code]
class SomeGroovyClass {

def field1 = ‘ha’
def field2 = ‘ho’

def getField1() {
return ‘getHa’
}
}

def someGroovyClass = new SomeGroovyClass()

assert someGroovyClass.metaClass.getAttribute(someGroovyClass, ‘field1’) == ‘ha’
assert someGroovyClass.metaClass.getAttribute(someGroovyClass, ‘field2’) == ‘ho’
[/code]

[code]
class POGO {

private String field
String property1

void setProperty1(String property1) {
this.property1 = "setProperty1"
}
}

def pogo = new POGO()
pogo.metaClass.setAttribute(pogo, ‘field’, ‘ha’)
pogo.metaClass.setAttribute(pogo, ‘property1’, ‘ho’)

assert pogo.field == ‘ha’
assert pogo.property1 == ‘ho’
[/code]

1.3 MethodMissing

Groovy支持methodMissing的概念。这个方法不同于invokeMethod,它只能在方法分发失败的情况下调用,当给定的名字或给定的参数无法找到时被调用:

[code]
class Foo {

def methodMissing(String name, def args) {
return "this is me"
}
}

assert new Foo().someUnknownMethod(42l) == ‘this is me’
[/code]

当我们使用methodMissing的时候,如果下一次同样一个方法被调用其返回的结果可能是缓存的。比如说,考虑在GORM的动态查找器,有一个methodMissing的实现,下面是具体的代码:

[code]
class GORM {

def dynamicMethods = […] // an array of dynamic methods that use regex

def methodMissing(String name, args) {
def method = dynamicMethods.find { it.match(name) }
if(method) {
GORM.metaClass."$name" = { Object[] varArgs ->
method.invoke(delegate, name, varArgs)
}
return method.invoke(delegate,name, args)
}
else throw new MissingMethodException(name, delegate, args)
}
}
[/code]

注意,如果我们发现一个方法要被调用,我们会使用ExpandoMetaClass动态注册一个新的方法在上面。这就是为什么下次相同的方法被调用将会更加快。使用methodMissing并没有invokeMethod的开销大。而且如果是第二次调用将基本没有开销。

1.4 propertyMissing

Groovy支持propertyMissing的概念,用于拦截可能存在的属性获取失败。在getter方法里,propertyMissing使用单个String类型的参数来代表属性名字:

[code]
class Foo {
def propertyMissing(String name) { name }
}

assert new Foo().boo == ‘boo’
[/code]

在Groovy运行时,propertyMissing(String)方法只有在没有任何getter方法可以被给定的property所找到才会被调用。
对于setter方法,可以添加第二个propertyMissing定义来添加一个额外的值参数

[code]
class Foo {
def storage = [:]
def propertyMissing(String name, value) { storage[name] = value }
def propertyMissing(String name) { storage[name] }
}

def f = new Foo()
f.foo = "bar"

assert f.foo == "bar"
[/code]

methodMissing方法的最适用地方在动态注册新的属性时能极大提供查找属性所花费的性能。
methodMissing和propertyMissing方法可以通过ExpandoMetaClass来添加静态方法和属性。

1.5 GroovyInterceptable

Groovy.lang.GroovyInterceptable接口是一个继承了GroovyObject的标记接口,在Groovy运行时,用于标记所有方法可以通过Groovy的方法分发机制被拦截。

[code]
package groovy.lang;

public interface GroovyInterceptable extends GroovyObject {
}
[/code]

当一个Groovy对象实现了GroovyInterceptable接口,它的invokeMethod()将在任何方法调用时被调用。下面是这个类型的一个简单示例:

[code]
class Interception implements GroovyInterceptable {

def definedMethod() { }

def invokeMethod(String name, Object args) {
‘invokedMethod’
}
}
[/code]

下一块代码是一个测试类,不管调用存在的方法还是不存在的方法都将返回相同的结果。

[code]
class InterceptableTest extends GroovyTestCase {

void testCheckInterception() {
def interception = new Interception()

assert interception.definedMethod() == ‘invokedMethod’
assert interception.someMethod() == ‘invokedMethod’
}
}
[/code]

我们不能使用默认的Groovy方法比如println,因为这些方法是被注入到Groovy对象中区,因此它们也会被拦截。
如果我们想拦截所有所有方法但又不想实现GroovyInterceptable接口,我们可以在一个对象的MetaClass类上实现invokeMethod()。对于POGOs和POJOs,这种方式都是可以的。下面是一个示例:

[code]
class InterceptionThroughMetaClassTest extends GroovyTestCase {

void testPOJOMetaClassInterception() {
String invoking = ‘ha’
invoking.metaClass.invokeMethod = { String name, Object args ->
‘invoked’
}

assert invoking.length() == ‘invoked’
assert invoking.someMethod() == ‘invoked’
}

void testPOGOMetaClassInterception() {
Entity entity = new Entity(‘Hello’)
entity.metaClass.invokeMethod = { String name, Object args ->
‘invoked’
}

assert entity.build(new Object()) == ‘invoked’
assert entity.someMethod() == ‘invoked’
}
}
[/code]

关于MetaClass类的详细信息可以在MetaClass章节找到。

1.6 Categories

有这样一种场景,如果能让一个类的某些方法不受控制将会是很有用的。为了实现这种可能性,Groovy从Object-C借用实现了一个特性,叫做Categories。
Categories特性实现了所谓的category类,一个category类是需要满足某些特定的预定义的规则来定义一些拓展方法。
下面有几个categories是在Groovy环境中系统提供的一些额外功能:

Category类默认是不能使用的,要使用这些定义在一个category类的方法需要使用 use 方法,这个方法是GDK提供的一个内置于Groovy对象中的实例:

[code]
use(TimeCategory) {
println 1.minute.from.now //(1)
println 10.hours.ago

def someDate = new Date() //(2)
println someDate – 3.months
}
[/code]

(1) TimeCategory添加一个方法到Integer
(2) TimeCategory添加一个方法到Date
use 方法把category类作为第一个参数,一个闭包代码块作为第二个参数。在Closure里可以访问catetory。从上面的例子可以看到,即便是JDK的类,比如java.lang.Integer或java.util.Date也是可以被包含到用户定义的方法里的。
一个category不需要直接暴露给用户代码,下面的示例说明了这一点:

[code]
class JPACategory{
// Let’s enhance JPA EntityManager without getting into the JSR committee
static void persistAll(EntityManager em , Object[] entities) { //add an interface to save all
entities?.each { em.persist(it) }
}
}

def transactionContext = {
EntityManager em, Closure c ->
def tx = em.transaction
try {
tx.begin()
use(JPACategory) {
c()
}
tx.commit()
} catch (e) {
tx.rollback()
} finally {
//cleanup your resource here
}
}

// user code, they always forget to close resource in exception, some even forget to commit, let’s not rely on them.
EntityManager em; //probably injected
transactionContext (em) {
em.persistAll(obj1, obj2, obj3)
// let’s do some logics here to make the example sensible
em.persistAll(obj2, obj4, obj6)
}
[/code]

如果我们去看groovy.time.TimeCategory类的嗲吗我们会发现拓展方法都是被声明为static方法。事实上,一个category类的方法要能被成功地加到use代码块里必须要这样写:

[code]
public class TimeCategory {

public static Date plus(final Date date, final BaseDuration duration) {
return duration.plus(date);
}

public static Date minus(final Date date, final BaseDuration duration) {
final Calendar cal = Calendar.getInstance();

cal.setTime(date);
cal.add(Calendar.YEAR, -duration.getYears());
cal.add(Calendar.MONTH, -duration.getMonths());
cal.add(Calendar.DAY_OF_YEAR, -duration.getDays());
cal.add(Calendar.HOUR_OF_DAY, -duration.getHours());
cal.add(Calendar.MINUTE, -duration.getMinutes());
cal.add(Calendar.SECOND, -duration.getSeconds());
cal.add(Calendar.MILLISECOND, -duration.getMillis());

return cal.getTime();
}

// …
[/code]

另外一个要求是静态方法的第一个参数必须定义类型,只要方法被激活。另外一个参数可以作为一个普通的参数当成方法的变量。
因为参数和静态方法的转变,category方法的定义可能比一般的方法定义不那么直观。不过Groovy提供了一个@Category注解,可以在编译时将一个类转化为category类。

[code]
class Distance {
def number
String toString() { "${number}m" }
}

@Category(Number)
class NumberCategory {
Distance getMeters() {
new Distance(number: this)
}
}

use (NumberCategory) {
assert 42.meters.toString() == ’42m’
}
[/code]

使用@Category注解可以直接使用示例方法二不必将目标类型作为第一个参数的好处。目标类型类在注解里作为了一个参数。
编译时元编程章节里有@Category的详细说明。

1.7 MetaClasses

(TBD)

1.7.1 Custom metaclasses

(TBD)
Delegating metaclass
(TBD)
Magic package(Maksym Stavyskyi)
(TBD)

1.7.2 Per instance metaclass

(TBD)

1.7.3 ExpandoMetaclass

Groovy有一个特殊的MetaClass类叫做ExpandoMetaClass。它的特别之处在于支持动态添加或修改方法,构造函数,属性,甚至通过使用一个闭包语法来添加或修改静态方法。
这些特性测试场景将会非常使用,具体在测试指南将会说明。
在Groovy里,每一个java.lang.Class类都有一个特殊的metaClass属性,可以通过它拿到一个ExpandoMetaCalss实例。这个实例可以被用于添加方法或修改一个已经存在的方法的行为。
默认ExpandoMetaCalss是不能被继承的,如果你需要这样做必须在你的应用启动前或servlet启动类前调用ExpandoMetaClass#enableGlobally()
下面的小节将详细说明如何在各种场景使用ExpandoMetaCalss。

Methods
一旦ExpandoMetaClass通过metaClass属性被调用,就可以使用<<或 = 操作符来添加方法。
注意 << 是用来添加新方法,如果一个方法已经存在使用它会抛出异常。如果你想替换一个方法可以使用 = 操作符。
对于一个不存在的metaClass属性通过传入一个闭包代码块实例来实现

[code]
class Book {
String title
}

Book.metaClass.titleInUpperCase &amp;amp;amp;amp;lt;&amp;amp;amp;amp;lt; {-&amp;amp;amp;amp;gt; title.toUpperCase() }

def b = new Book(title:"The Stand")

assert "THE STAND" == b.titleInUpperCase()
[/code]

上面的示例演示了如何通过metaClass属性使用 << 或 = 操作符赋值到一个闭包代码块将一个新方法添加到一个类。闭包参数将作为方法参数被拦截。不确定的方法参数可以使用{→ …} 语法。
Properties
ExpandoMetaClass支持两种添加或重载属性的机制。
第一种,支持通过赋值到一个metaCalss属性来声明一个可变属性。

[code]
class Book {
String title
}

Book.metaClass.author = "Stephen King"
def b = new Book()

assert "Stephen King" == b.author
[/code]

第二种使用标准机制来添加getter或 setter方法:

[code]
class Book {
String title
}
Book.metaClass.getAuthor &amp;amp;amp;amp;lt;&amp;amp;amp;amp;lt; {-&amp;amp;amp;amp;gt; "Stephen King" }

def b = new Book()

assert "Stephen King" == b.author
[/code]

上面的示例代码中,闭包里的属性是一个制度属性。当然添加一个类似的setter方法也是可行的,但是属性值需要被存储起来。具体可以看下面的示例:

[code]
class Book {
String title
}

def properties = Collections.synchronizedMap([:])

Book.metaClass.setAuthor = { String value -&amp;amp;amp;amp;gt;
properties[System.identityHashCode(delegate) + "author"] = value
}
Book.metaClass.getAuthor = {-&amp;amp;amp;amp;gt;
properties[System.identityHashCode(delegate) + "author"]
}
[/code]

当然,这不仅仅是一个技术问题。比如在一个servlet容器里一种存储值得方法是放到当前request中作为request的属性。(Grails也是这样做的)
Constructors
构造函数可以通过constructor属性来添加,也可以通过闭包代码块使用 << 或 = 来添加。在运行时闭包参数将变成构造函数参数。

[code]
class Book {
String title
}
Book.metaClass.constructor &amp;amp;amp;amp;lt;&amp;amp;amp;amp;lt; { String title -&amp;amp;amp;amp;gt; new Book(title:title) }

def book = new Book(‘Groovy in Action – 2nd Edition’)
assert book.title == ‘Groovy in Action – 2nd Edition’
[/code]

添加构造函数的时候需要注意,很容易导致栈溢出问题。
Static Methods
静态方法可以通过同样的技术来实现,仅仅是比实例方法的方法名字前多一个static修饰符。

[code]
class Book {
String title
}

Book.metaClass.static.create &amp;amp;amp;amp;lt;&amp;amp;amp;amp;lt; { String title -&amp;amp;amp;amp;gt; new Book(title:title) }

def b = Book.create("The Stand")
[/code]

Borrowing Methods
使用ExpandoMetaClass,可以实现使用Groovy方法指针从其他类中借用方法。

[code]
class Person {
String name
}
class MortgageLender {
def borrowMoney() {
"buy house"
}
}

def lender = new MortgageLender()

Person.metaClass.buyHouse = lender.&amp;amp;amp;amp;amp;borrowMoney

def p = new Person()

assert "buy house" == p.buyHouse()
[/code]

动态方法名(Dynamic Method Names)
因为Groovy支持你使用字符串作为属性名同样也支持在运行时动态创建方法和属性。要创建一个动态名字的方法仅仅使用引用属性名作为字符串这一特性即可。

[code]
class Person {
String name = "Fred"
}

def methodName = "Bob"

Person.metaClass."changeNameTo${methodName}" = {-&amp;amp;amp;amp;gt; delegate.name = "Bob" }

def p = new Person()

assert "Fred" == p.name

p.changeNameToBob()

assert "Bob" == p.name
[/code]

同样的概念可以用于静态方法和属性。
在Grails网络应用程序框架里我们可以找到动态方法名字的实例。“动态编码”这个概念就是动态方法名字的具体实现。
HTMLCodec类

[code]
class HTMLCodec {
static encode = { theTarget -&amp;amp;amp;amp;gt;
HtmlUtils.htmlEscape(theTarget.toString())
}

static decode = { theTarget -&amp;amp;amp;amp;gt;
HtmlUtils.htmlUnescape(theTarget.toString())
}
}
[/code]

上面的代码演示了一种编码的实现。Grails对于每个类都有很多编码实现可用。在运行时可以配置多个编码类在应用程序classpath里。在应用程序启动框架里添加一个encodeXXX和一个decodeXXX方法到特定的meta-classes类。XXX是编码类的第一部分(比如encodeHTML)。这种机制在Groovy预处理代码中如下:

[code]
def codecs = classes.findAll { it.name.endsWith(‘Codec’) }

codecs.each { codec -&amp;amp;amp;amp;gt;
Object.metaClass."encodeAs${codec.name-‘Codec’}" = { codec.newInstance().encode(delegate) }
Object.metaClass."decodeFrom${codec.name-‘Codec’}" = { codec.newInstance().decode(delegate) }
}

def html = ‘&amp;amp;amp;amp;lt;html&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;body&amp;amp;amp;amp;gt;hello&amp;amp;amp;amp;lt;/body&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;/html&amp;amp;amp;amp;gt;’

assert ‘&amp;amp;amp;amp;lt;html&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;body&amp;amp;amp;amp;gt;hello&amp;amp;amp;amp;lt;/body&amp;amp;amp;amp;gt;&amp;amp;amp;amp;lt;/html&amp;amp;amp;amp;gt;’ == html.encodeAsHTML()
[/code]

Runtime Discovery
在运行时,当方法被执行的时候如果知道其他方法或属性的存在性是非常有用的。ExpandoMetaClass提供了下面的方法来获取:

  • getMetaMethod
  • hasMetaMethod
  • getMetaProperty
  • hasMetaProperty

为何不直接使用反射?因为Groovy不同于Java,Java的方法是真正的方法并且只能在运行时存在。Groovy是(并不总是)通过MetaMethods来呈现。MetaMethods告诉你在运行时哪些方法可用,因此你的代码可以适配。
重载invokeMethod,getProperty和setProperty是一种特别的用法。
GroovyObject Methods
ExpandoMetaClass的另外一个特点是支持重载invokeMethod,getProperty和setProperty。这些方法可以在groovy.lang.GroovyObject类里找到。
下面的代码演示了如何重载invokeMethod方法:

[code]
class Stuff {
def invokeMe() { "foo" }
}

Stuff.metaClass.invokeMethod = { String name, args -&amp;amp;amp;gt;
def metaMethod = Stuff.metaClass.getMetaMethod(name, args)
def result
if(metaMethod) result = metaMethod.invoke(delegate,args)
else {
result = "bar"
}
result
}

def stf = new Stuff()

assert "foo" == stf.invokeMe()
assert "bar" == stf.doStuff()
[/code]

在闭包代码里,第一步是通过给定的名字和参数查找MetaMethod。如果一个方法准备就绪就委托执行,否则将返回一个默认值。
MetaMethod是一个存在于MetaClass上的方法,可以在运行时和编译时被添加进来。
同样的逻辑可以用来重载setProperty和getProperty

[code]
class Person {
String name = "Fred"
}

Person.metaClass.getProperty = { String name -&amp;amp;amp;gt;
def metaProperty = Person.metaClass.getMetaProperty(name)
def result
if(metaProperty) result = metaProperty.getProperty(delegate)
else {
result = "Flintstone"
}
result
}

def p = new Person()

assert "Fred" == p.name
assert "Flintstone" == p.other
[/code]

这里值得注意的一个重要问题是不是MetaMethod而是MetaProperty实例将会查找。如果一个MetaProperty的getProperty方法已经存在,将会直接调用。

重载Static invokeMethod

ExpandoMetaClass甚至允许重载静态方法,通过一个特殊的invokeMethod语法

[code]
class Stuff {
static invokeMe() { "foo" }
}

Stuff.metaClass.’static’.invokeMethod = { String name, args -&amp;amp;amp;gt;
def metaMethod = Stuff.metaClass.getStaticMetaMethod(name, args)
def result
if(metaMethod) result = metaMethod.invoke(delegate,args)
else {
result = "bar"
}
result
}

assert "foo" == Stuff.invokeMe()
assert "bar" == Stuff.doStuff()
[/code]

重载静态方法的逻辑和前面我们见到的从在实例方法的逻辑一样。唯一的区别在于方位metaClass.static属性需要调用getStaticMethodName作为静态MetaMehod实例的返回值。

Extending Interfaces

有时候我们需要在ExpandoMetaClass接口里添加方法,为实现这个,必须支持在应用启动前全局支持ExpandoMetaClass.enableGlobally()方法。

[code]
List.metaClass.sizeDoubled = {-&amp;amp;amp;gt; delegate.size() * 2 }

def list = []

list &amp;amp;amp;lt;&amp;amp;amp;lt; 1
list &amp;amp;amp;lt;&amp;amp;amp;lt; 2

assert 4 == list.sizeDoubled()
[/code]

1.8 拓展模型

1.8.1 拓展已经存在的类

拓展模型允许你添加新方法到已经存在的类中。这些类包括预编译类,比如JDK中的类。这些新方法不同于使用metaclass或category,可以全局使用。比如,
标准拓展方法:

[code]
def file = new File(…)
def contents = file.getText(‘utf-8’)
[/code]

getText方法不存在于File类里,当然,Groovy知道它定义在一个特殊的类里,ResourceGroovyMethods:
ResourceGroovyMethods.java

[code]
public static String getText(File file, String charset) throws IOException {
return IOGroovyMethods.getText(newReader(file, charset));
}
[/code]

你可能已经注意到,这个拓展方法在一个帮助类(定义了各种各样的拓展方法)中使用了static方法来定义。getText方法的第一个参数和传入值应该一直,额外的参数和拓展方法的参数一致。这里我们就定义了File类的getText方法。这个方法进接受一个参数(String类型)。
创建一个拓展模型非常简单

  • 写一个像上面类似的拓展类
  • 写一个模块描述文件

下一步你需要使拓展模型对Groovy可见,需要将拓展模型类和可用的描述类添加到类路径。这意味着你有以下选择:

  • 要么直接在类路径下提供类文件和模块描述文件
  • 或者将拓展模块打包成jar包以便重用

拓展模块有两种方法添加到一个类中

  • 实例方法(也叫作一个类的实例)
  • 静态方法(也叫作类方法)

1.8.2 实例方法

要添加一个实例方法到一个已经存在的类,你需要创建一个拓展类。举个例子,你想添加一个maxRetries放到到Integer类里,它接收一个闭包只要不抛出异常最多执行n次。你需要写下面的代码:

[code]
class MaxRetriesExtension { //(1)
static void maxRetries(Integer self, Closure code) { //(2)
int retries = 0
Throwable e
while (retries&amp;amp;lt;self) {
try {
code.call()
break
} catch (Throwable err) {
e = err
retries++
}
}
if (retries==0 &amp;amp;amp;&amp;amp;amp; e) {
throw e
}
}
}
[/code]

(1)拓展类
(2)静态方法的第一个参数和接收的信息一致,也就是拓展实例
下一步,声明了拓展类之后,你可以这样调用它:

[code]
int i=0
5.maxRetries {
i++
}
assert i == 1
i=0
try {
5.maxRetries {
throw new RuntimeException("oops")
}
} catch (RuntimeException e) {
assert i == 5
}
[/code]

1.8.3 静态方法

Groovy支持添加一个静态方法到一个类里,这种情况静态方法必须定义在自己的文件里。静态和实例拓展方法不能再同一个类里。

[code]
class StaticStringExtension { //(1)
static String greeting(String self) { //(2)
‘Hello, world!’
}
}
[/code]

(1)静态拓展类
(2)静态方法的第一个从那时候和被拓展的保持一致
这个例子,可以直接从String类里调用

[code]
assert String.greeting() == ‘Hello, world!’
[/code]

1.8.4 模块描述

Groovy允许你加载自己的拓展类,你必须声明你的拓展帮助类。你必须创建一个名为org.codehaus.groovy.runtime.ExtensionModule 到META-INF/services 目录里:
org.codehaus.groovy.runtime.ExtensionModule

[code]
moduleName=Test module for specifications
moduleVersion=1.0-test
extensionClasses=support.MaxRetriesExtension
staticExtensionClasses=support.StaticStringExtension
[/code]

模块描述需要4个主键

  • moduleName:你的模块名字
  • moduleVersion:你的模块版本号。注意版本号仅仅用于检验你是否有将两个不同的版本导入同一个模块
  • extensionClasses:拓展帮助类中实例方法列表,你可以提供好几个类,使用逗号分隔
  • staticExtensionClasses:拓展帮助类中静态方法裂列表,你可以提供好几个类,使用逗号分隔

注意并不要求一个模块既定义静态帮助类又定义实例帮助类,你可以添加好几个类到单个模块,也可以拓展不同类到单个模块。还可以使用不同的类到单个拓展类,但是建议根据特性分组拓展方法。

1.8.5 拓展模块和类路径

你不能将一个编译好了的拓展类当成源码一样使用。也就是说使用一个拓展必须在类路径下,而且是一个已经编译好了的类。同城,你不能太拓展类里添加测试类。因为测试类通常和正式源码会分开。

1.8.6 类型检查能力

不像categories,拓展模块是编译后的类型检查。如果不能在类路径下找到,当你调用拓展方法时类型检查将会识别出来。对于静态编译也一样。

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: 运行时和编译时元编程—运行时元编程

  • Trackback 关闭
  • 评论 (0)
  1. 暂无评论

return top