Instantiated a class, but it appears referenced to null

126 Views Asked by At

I'm trying to instantiate an object and set a single attribute on it, which comes from a request parameter, like so :

println "Question text from the request :" + params.question

def question = new SurveyQuestion()
question.question = params.question

println "this is our question" + question

This is my output in the console :

Question text from the request :test this is our questionroosearch.SurveyQuestion : null

And this is the SurveyQuestion class :

class SurveyQuestion {

    String question

    static hasMany = [responses : SurveyQuestionResponse]
    static belongsTo = [survey: Survey]

    static constraints = {
    }
}

The above seems to compile ok, however I get further classcast exceptions when I do a redirect at the end of my action, I believe this is due to the instantiating and setting of that SurveyQuestion, as if I comment out the above I don't get this failure behaviour.

Am I instantiating the SurveyQuestion object correctly? Why does it display as null when I print it to the console? Is that normal behaviour? At the least I'd expect it to print the object reference as Java would?

Thanks

1

There are 1 best solutions below

0
On

The default toString() method on a domain instance will return a string which looks like class.name: id. As your newly created domain instance doesn't have id set is shows null.

Try overriding toString() in your SurveyQuestion domain:

String toString() {
    return question
}