Question

I am using builder pattern but after setting the feilds its returning nullpointerException:

package com.test.sample1;

 public class MessageID {

public int BOI1;
public int DOI2;
public int CO3;

public MessageID(int BOI1,int DOI2,int CO3){
    this.BOI1=BOI1;
    this.DOI2=DOI2;
    this.CO3=CO3;
}


public int getBOI1(){
    return BOI1;
}
public int getDOI2(){
    return DOI2;
}
public int CO3(){
    return CO3;
    }
 }

here is the BaseServiceRequest.java ::

        package com.test.sample;

        import com.test.sample1.MessageID;

        public class BaseServiceRequest   {


             MessageID messageID;

            public BaseServiceRequest(BaseServiceRequestBuilder builder) {
                this.messageID = builder.messageID;

            }

            public MessageID getMessageID() {

                return messageID;
            }

            public static class BaseServiceRequestBuilder {

                private MessageID messageID;

                public BaseServiceRequestBuilder messageID(MessageID messageID) {   
                    this.messageID =messageID;      
                return this;
                }

            }
        }

here is the main class::

       package com.test.sample;

      import com.test.sample.BaseServiceRequest.BaseServiceRequestBuilder;
      import com.test.sample1.MessageID;

      public class Wrapper {

        static BaseServiceRequestBuilder builder = new BaseServiceRequestBuilder();
        static BaseServiceRequest request;

  public static void main(String[] args) {
    test(builder);
    int syso = request.getMessageID().getBOI1();
    System.out.println(syso);

  }

   public static void test(BaseServiceRequestBuilder builder) {
   builder.messageID(new MessageID(23, 34, 12));
  }

  }

I should get a output of 23 at request.getMessageID().getBOI1(),
but getting a null pointer Exception

Était-ce utile?

La solution

That's because you're invoking the builder's build method and throwing the result away. Save the result:

request = builder.messageID(new MessageID(23, 34, 12));

Note that this isn't really an example of the Builder pattern; it's really a Factory. Most useful Builder classes use a fluent API to make the process clear and less bug-prone, and the Builder object contains the intermediate state necessary to construct the new instance, such as this:

request = new BaseServiceRequestBuilder().boi1(23).doi2(34).co3(12).build();

If you already had the MessageID object, perhaps from some incoming request, the Builder might also accept it as a parameter:

request = new BaseServiceRequestBuilder().messageID(id).build();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top