简体   繁体   中英

How to call parameterized constructor from another class in java

I have a class in Java that looks like this:

  public class UserUrl{
    
        public final MongoUserId mongoUserId;
        public final Optional<String> url;
        public final long version;
        public final Instant requestedDate;
        public final Instant createdDate;
        public final State state;

public UserUrl(MongoUserId mongoUserId,
                   Optional<String> url,
                   long version,
                   Instant requestedDate,
                   Instant createdDate, State state) {
        this.mongoUserId = mongoUserId;
        this.url = url;
        this.version = version;
        this.requestedDate = requestedDate;
        this.createdDate = createdDate;
        this.state = state;
    }
    
        public UserUrl withUrl(String url){
            return new UserUrl(
                    this.mongoUserId,
                    Optional.of(url),
                    1,
                    this.requestedDate,
                    Instant.now(),
                    State.COMPLETED
            );
        }
    }

I want to access constructor from another class, and I am trying to do it like this:

 UserUrl userUrl = new UserUrl();
 userUrlRepository.save(userUrl.withUrl(url));

But I am not able because

UserUrl userUrl = new UserUrl();

is looking for parameters.

What is good way of doing this?

Well, I think you're missing something here. I there is not a no-arg constructor, you obviously cannot call it, since it doesn't exist.

You have two options here.

  • Either declare a no-arg constructor:

     UserUrl() { // Optionally initialize your properties with default values. }
  • Or use the existing constructor:

     UserUrl userUrl = new UserUrl(null, Optional.of(url), 1, null, Instant.now(), State.COMPLETED); userUrlRepository.save(userUrl); // No need to set the URL

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