[英]How can I call parameterized constructor of default type from a parameterized constructor of type public which is in another class?
[英]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.