简体   繁体   中英

NullPointerException when accessing static variable in another class in Java

I have trying to access a static variable of class A in class B, however I am getting NullPointerException. The code is :

public class OutgoingMessage {
    public static SMPPSession session;
    public static void main(String [] args)
    {
         session = new SMPPSession();

    }
  }

And

public class SendSMS {
    public static void main(String [] args)
    {
      if(OutgoingMessage.session.getSessionState().toString().equals("Connected"))//Line 44 
        {
        }
    } 
}

The error reads

Exception in thread "main" java.lang.NullPointerException
        at SendSMS.main(SendSMS.java:44)

Any idea what am I missing ?

Thanks

Satya

Sure - you're using OutgoingMessage.session , which will be null unless you've also run OutgoingMessage.main . It's not like main methods get invoked automatically everywhere - that's just the entry point for the application.

I suggest that instead of changing this to use a static initializer or something like that, you try to work to avoid static variables.

Why would it make sense for OutgoingMessage to have a static session variable? I'd expect the two to work together, not one be composed of the other... for example, I could imagine:

SMPPSession session = new SMPPSession();
session.send(outgoingMessage);

or even:

SMPPSession session = new SMPPSession();
outgoingMessage.sendInSession(session);

OutgoingMessage.session is null at the point where you are calling

if(OutgoingMessage.session.getSessionState()

Which results in NullPointerException .

Make sure OutgoingMessage class main method is executed before making if(OutgoingMessage.session.getSessionState()

Unless you use OutgoingMessage as main class, it doesn't make sense to define main method there, which confuses more.

You can add OutgoingMessage.main(args); before:

if(OutgoingMessage.session.getSessionState().toString().equals("Connected")) //Line 44 ...

您在OutgoingMessage中缺少静态的getter方法,并且只需要一个main方法。

The problem is when you use OutgoingMessage.session it is not yet initialized. To correctly initialize it do:

public class OutgoingMessage {
    public static SMPPSession session = new SMPPSession();
  }

You haven't initialized your static variable.. That's why..

Actually you have done that in main() , but that will really not affect your output.. As your main will never be run.. You can initialize it at the place of declaration only..

public static SMPPSession session = new SMPPSession();

Before main method.. But it doesn't make sense to have it as static variable..

You should declare it as instance variable and initialize it for each instance you create using a Constructor ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM