If you've a domain class in a grails project you can also use getter and setter to write or read them.
For example domain class Book has attribute:
String author
In controller you've a book and you want to set the author for this book:
This works with direct access to the attribute or with getter and setter methods although they aren't in the class.
book.author = "Mike Miller"
book.setAuthor("Mike Miller")
What's the preferred way of getting and setting attributes in groovy & grails?
Best Answer
They're the same. When you have an unscoped field like
String author
, the Groovy compiler makes the field private and creates a getter and setter for it. It won't overwrite existing methods though, so you can define your own set and/or get if it's more than just setting and getting the value.book.author = "Mike Miller"
is Groovy syntactic sugar for calling the setter, just likeString authorName = book.author
is syntactic sugar for calling the getter. To see this, edit the class and add in a setter or getter and add a println, e.g.You can use a decompiler to see the generated code - I recommend JD-GUI, http://java.decompiler.free.fr/?q=jdgui