簡體   English   中英

如何從java中的另一個類調用參數化構造函數

[英]How to call parameterized constructor from another class in java

我有一個 Java 類,如下所示:

  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
            );
        }
    }

我想從另一個類訪問構造函數,我正在嘗試這樣做:

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

但我不能因為

UserUrl userUrl = new UserUrl();

正在尋找參數。

這樣做的好方法是什么?

好吧,我認為你在這里遺漏了一些東西。 我沒有無參數構造函數,你顯然不能調用它,因為它不存在。

您在這里有兩個選擇。

  • 要么聲明一個無參數構造函數:

     UserUrl() { // Optionally initialize your properties with default values. }
  • 或者使用現有的構造函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM