I have a bunch of Java classes that I would like to use as command classes in my Grails contollers. A typical example is:
class Person {
String name
Integer age
public String getName() {return name;}
public String getAge() {return age;}
public void setName(String name) {this.name = name;}
public void setAge(Integer age) {this.age = age;}
}
I would like to able to specify constraints for this class such that I can call validate()
on it, and any validation errors will be stored in theerrors
property. In other words, it will behave just like a regular Grails command class.
Obviously I can't declare the constraints closure directly in the .java source file, because Java doesn't support closures. Is there some way I can modify these classes (at runtime), to add Grails command behaviour?
I haven't tried this but you could use Groovy's meta-programming capabilities to achieve this. In your
Bootstrap.groovy
you could add the staticcontraints
closure to all the Java classes that you want to validate. Also annotate your classes with@Validateable
. Here's an example:Afterwards treat these classes like Command classes to validate them.