Grails - 无法在null对象上调用方法getAt()

时间:2013-02-06 16:13:13

标签: exception grails groovy null

我在尝试将图书附加到课程列表列表时遇到错误。关于为什么或我可以做些什么来修复它的任何想法?

        //For each book in a class...
        for (int k = 0; k < rows.size(); k++) {
            Book book = new Book()

            //Assign the values to a new book object
            book.id            = rows[k].getProperty("ISBN")
            book.title         = rows[k].getProperty("title")
            book.author        = rows[k].getProperty("author")
            book.required      = rows[k].getProperty("required_optional")
            book.purchaseType  = rows[k].getProperty("rental_purchase")
            //book.purchasePrice = rows[k].getProperty("purchase_price")
            //book.rentalPrice   = rows[k].getProperty("rental_fee")

            //Append the book to the books list object in the particular class
            classes[i].books[k + 1] << book
        }

3 个答案:

答案 0 :(得分:1)

而不是[]使用getAt进行访问,?运算符将起作用:

classes?.getAt(i)?.books?.getAt(k+1) << book

classes?.getAt(i)?.books[k+1] << book

答案 1 :(得分:0)

没有完整的代码,很难知道会发生什么。试试这段代码,它会显示哪个值为null:

// first check if classes[i] is null, add error handling if it is
if (classes[i]!=null) {
    //For each book in a class...
    for (int k = 0; k < rows.size(); k++) {     
        def books = classes[i].books[k + 1]
        if (books!=null) {
            // you can set values directly here
            def row = rows[k]
            Book book = new Book(
                id: k.getProperty("ISBN"),
                title: k.getProperty("title")
                // ...
            )
            //Append the book to the books list object in the particular class
            books << book
        } else {
            println "books is null, do something clever"
        }
    }
} else {
    println "classes[i] is null, do something clever"
}

我没有测试它,你可以用一些时髦的善良来缩短它。这只是为了让你开始

答案 2 :(得分:0)

我不确定'类'是什么,但如果它是一个包含'Book'的列表,你可以做到

classes << book

OR

classes.add(book)