Soccertrash
Soccertrash

Reputation: 1901

CompoundPropertyModel Wicket - Object graphs

I'd like to use the CompoundPropertyModel in Wicket for creating a user.

My user class looks like this:

    public class User {
      private String username;
      ...
      private Address address;
      ...
     }

    public class Address{
      private String street;
      ...
     }

If I try to access the street of the address via the User's compoundproperty model, I get a nullpointerexception, of course: "user.address.street". So I have to instantiate the class "Address" on my own in advance. Is there a more elegant way to dynamically instantiate member fields?

Thanks

Upvotes: 0

Views: 191

Answers (1)

Daniel Semmens
Daniel Semmens

Reputation: 461

If a User must have an Address, you should create the instance of Address in the constructor for the User. Otherwise, you might do a null check in your getAddress() method and create a new instance if it's null...

public Address getAddress() {
    if (address == null) {
        address = new Address();
    }

    return address;
}

Upvotes: 3

Related Questions