groovy - Groovy 中是否自动定义了访问器/修改器?

标签 groovy

在《Groovy In Action》中关于使用 Groovy 处理 Java Bean 的部分中,我发现了这个脚本(稍作修改):

class Book{
  String title
}
def groovyBook = new Book()
// explicit way
groovyBook.setTitle('What the heck, really ?')
println groovyBook.getTitle()
// short-hand way
groovyBook.title = 'I am so confused'
println groovyBook.title  

Book 类中没有这样的方法,那么它是如何工作的呢?

最佳答案

是的,它们是自动定义的,调用 book.title 实际上是调用 book.getTitle()

参见http://groovy.codehaus.org/Groovy+Beans

您可以使用以下脚本查看此操作:

def debug( clazz ) {
    println '----'
    clazz.metaClass.methods.findAll { it.name.endsWith( 'Name' ) || it.name.endsWith( 'Age' ) }.each { println it }
}

class A {
    String name
    int age
}
debug( A )
// Prints
// public int A.getAge()
// public java.lang.String A.getName()
// public void A.setAge(int)
// public void A.setName(java.lang.String)

// Make name final
class B {
    final String name
    int age
}
debug( B )
// Prints
// public int B.getAge()
// public java.lang.String B.getName()
// public void B.setAge(int)

// Make name private
class C {
    private String name
    int age
}
debug( C )
// Prints
// public int C.getAge()
// public void C.setAge(int)

// Try protected
class D {
    protected String name
    int age
}
debug( D )
// Prints
// public int D.getAge()
// public void D.setAge(int)

// And public?
class E {
    public String name
    int age
}
debug( E )
// Prints
// public int E.getAge()
// public void E.setAge(int)

关于groovy - Groovy 中是否自动定义了访问器/修改器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089988/

相关文章:

multithreading - groovy 多线程

grails - FormService中的未知类型 'processDefinition'

grails - 对Grails数据源插件使用唯一约束会导致NullPointerException

performance - 常规 : closures significantly slower than methods?

java - 注入(inject)和配置 Gradle 构建

java - GEB:驱动程序未设置为 Browser.driver

grails - 将简单的grails(1.3.7)WAR文件部署到JBoss 7.0.1

java - 对 Java、Groovy、Jython 和 Python 进行基准测试

java - 在类初始化期间确定的唯一枚举名称标记

mongodb - Grails GORM动态查找器和条件不适用于MongoDB