调用方法时发生java.lang.NullPointerException

时间:2014-12-28 18:58:16

标签: java oop nullpointerexception

我在调用java.lang.NullPointerException时收到sendToAll(name)

public clientThreader(Socket cliSocket)
{
    try
    {
        outSocket = cliSocket;
        readStream = new ObjectInputStream(outSocket.getInputStream());
        String name = (String)readStream.readObject();
        totConnected++;
        clientNames.add(name);
        System.out.println(name+" is connected");

        if(name!=null)
            sendToAll(name);
    }
    catch(Exception e)
    {
        System.out.println("Fail here");
        e.printStackTrace();
    }
}

它不会进入被调用的方法并导致此输出:

java.lang.NullPointerException
    at chatServer.sendToAll(chatServer.java:60)
    at chatServer.access$200(chatServer.java:5)
    at chatServer$clientThreader.<init>(chatServer.java:110)
    at chatServer.setUpServer(chatServer.java:44)
    at chatServer.start(chatServer.java:29)
    at chatServer.main(chatServer.java:14)

我不明白我得到这个例外的原因是什么。

编辑:第60行是下面的语句allCli.equals(null)

private void sendToAll(String newCli)
{
    for( ObjectOutputStream allCli : clientOutStreams)
    {
        if(!(allCli.equals(null))) //line 60
        {
            try
            {
                System.out.println("here");
                allCli.writeObject(newCli);
                System.out.println("here");
            }
            catch(Exception sendFail)
            {
                System.out.println("SendToAll Failed");
                sendFail.printStackTrace();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

if(!(allCli.equals(null)))更改为if(allCli != null)

答案 1 :(得分:0)

if条件从!(allCli.equals(null))更改为allCli != null。您获得NullPointerException的原因是因为null对象没有您可以调用的.equals方法。