Java界面问题

时间:2010-06-19 16:31:26

标签: java interface nullpointerexception

我有一个界面:

package com.aex;

import javax.jws.WebParam;

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

上课:

    /*
 * 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;
    }

}

现在我想通过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;
    }

}

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

1 个答案:

答案 0 :(得分:5)

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

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

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

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