Java界面问题

Jul*_*ian 1 java interface nullpointerexception

我有一个界面:

package com.aex;

import javax.jws.WebParam;

public interface IFonds {
    double getKoers();
    String getNaam();
    void setKoers(@WebParam(name="koers") double koers); }
Run Code Online (Sandbox Code Playgroud)

和班级:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aex;

import java.io.Serializable;
import javax.jws.*;

/**
 *
 * @author Julian
 */
@WebService
public class Fonds implements IFonds, Serializable {

    String naam;
    double koers;

    public double getKoers() {
        return koers;
    }

    public String getNaam() {
        return naam;
    }

public Fonds()
{
}

    public Fonds(String naam,  double koers)
    {
        this.naam = naam;
        this.koers = koers;

    }

    public void setKoers(@WebParam(name="koers")double koers) {
        this.koers = koers;
    }

}
Run Code Online (Sandbox Code Playgroud)

现在我想通过webservice发送一个接口集合,所以这是我发送的类:

package com.aex;

import java.util.Collection;
import java.util.*;
import javax.jws.*;

/**
 *
 * @author Julian
 */
@WebService
public class AEX implements IAEX {

    Collection<IFonds> fondsen;

    public Collection<IFonds> getFondsen() {
        return fondsen;
    }


    public AEX()
    {
        IFonds fonds1 = new Fonds("hema", 3.33);


        //fondsen.add(fonds1);
    }

    public double getKoers(@WebParam(name="fondsnaam")String fondsNaam){

        Iterator iterator = fondsen.iterator();

        while(iterator.hasNext())
        {
            Fonds tempFonds = (Fonds)iterator.next();
            if(tempFonds.getNaam().endsWith(fondsNaam))
            {
                return tempFonds.getKoers();
            }

        }
        return -1;
    }

}
Run Code Online (Sandbox Code Playgroud)

问题是我在最后显示的类(AEX)的构造函数中得到了nullpointerexception.这是因为我想将对象添加到接口集合中.有人有解决方案吗?

Jon*_*eet 5

是的:初始化您的集合变量!

public AEX()
{
    IFonds fonds1 = new Fonds("hema", 3.33);

    // This is the line you were missing
    fondsen = new ArrayList<IFonds>();
    fondsen.add(fonds1);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这实际上与接口或Web服务无关...引用类型字段默认为null,除非您显式初始化它们,无论上下文如何.