使用ExpandoMetaClass添加构造函数

在写测试用例的时候, 要构造测试数据, 发现有一个类没有默认的构造函数, 而又不希望使用用户定义的构造函数, 另外也不想修改生产源代码, 因此需要添加一个默认的构造函数. 使用Groovy的ExpandoMetaClass就可以实现, 具体文章看这里( http://groovy.codehaus.org/ExpandoMetaClass+-+Constructors)
通过ExpandoMetaClass增加构造函数和增加方法有些不同, 不过其本质是给constructor 这个"特殊"的属性通过<<或=操作符赋一个闭包, 而参数就是该构造函数的参数.
class Book {
    String title
}
Book.metaClass.constructor << { String title -> new Book(title:title) }
def b = new Book("The Stand")


不过这里有一点需要特别注意, 如果需要覆盖原有的默认构造函数, 有可能出现堆栈溢出, 比如这样写:
class Book {
    String title
}
Book.metaClass.constructor = {  new Book() }
def b = new Book("The Stand")


其原因是因为通过Groovy的MetaClass循环调用了相同的默认构造函数, 避免出现这种情况的做法是使用Spring的BeanUtils方法:
class Book {
    String title
}
Book.metaClass.constructor = {  BeanUtils.instantiateClass(Book) }

def b = new Book("The Stand")

你可能感兴趣的:(spring,groovy)