Ben
Ben

Reputation: 62356

Unable to initialize class with my list

I'm not able to get rid of this NullPointerException in the following class. My controller is extending this class and the problem goes away when I comment out the constructor below... what am I doing wrong?

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contentController' defined in file [C:\Users\bkuhl\JavaProjects\cmt\cmt\target\cmt\WEB-INF\classes\com\site\cmt\web\ContentController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.fettergroup.cmt.web.ContentController]: Constructor threw exception; nested exception is java.lang.NullPointerException

public class Controller {
    private List<String> cssFiles;
    private List<String> jsFiles;

    public Controller () {
        this.addCss("global.css");
        this.addJs("global.js");
    }

    public ModelAndView render (ModelAndView model) {

        //add Js & Css files
        model.addObject("cssFiles", this.cssFiles);
        model.addObject("jsFiles", this.jsFiles);

        return model;
    }

    /*
     * Add a css file to the page
     */
    public final void addCss (String cssPath) {
        cssFiles.add(this.cssFiles.size(), cssPath);
    }

    /*
     * Add a javascript file to the page
     */
    public final void addJs (String jsPath) {
        jsFiles.add(this.jsFiles.size(), jsPath);
    }
}

Upvotes: 0

Views: 171

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38511

public Controller () {
    this.cssFiles = new ArrayList<String>();
    this.jsFiles = new ArrayList<String>();
    this.addCss("global.css");
    this.addJs("global.js");
}

and why do you do this :

public final void addCss (String cssPath) {
    cssFiles.add(this.cssFiles.size(), cssPath);
}

public final void addJs (String jsPath) {
    jsFiles.add(this.jsFiles.size(), jsPath);
}

No need for the first argument really...

Upvotes: 0

Steve Kuo
Steve Kuo

Reputation: 63054

cssFiles and jsFiles were never explicitly initialized and are thus null. You should initialize them with a List implementation such as ArrayList.

private List<String> cssFiles = new ArrayList<String>();
private List<String> jsFiles = new ArrayList<String>();

When you declare a field (class variable) and don't assign it, the value defaults null (for references), 0 (for numbers) or false (boolean).

Upvotes: 3

Related Questions