我已经为 Java 中的选项创建了一个解决方案。
public final class Optional<T> {
private final T reference;
private Optional(T reference) {
this.reference = reference;
}
public T get() {
if (!isPresent()) {
throw new IllegalStateException("Cannot retrieve reference when absent!");
}
return reference;
}
public boolean isPresent() {
return reference != null;
}
public static <T> Optional<T> of(T reference) {
return new Optional<T>(reference);
}
public static <T> Optional<T> absent() {
return of(null);
}
public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
return of(nullableReference);
}
}
但是当我在生产代码中使用它时,编译器会抱怨。
这是我的生产代码:
public final class OnsetSequencer {
private final Onset onset;
private final Optional<EventManager> eventManager;
public OnsetSequencer(Onset onset, Optional<EventManager> eventManager) {
this.onset = onset;
this.eventManager = eventManager;
}
public OnsetSequencer(Onset onset) {
this(onset, Optional.absent());
}
public void sequence() {
boolean present = eventManager.isPresent();
if (present) {
eventManager.get().dispatchEvent(new OnsetBeginEvent(onset));
}
onset.begin();
if (present) {
eventManager.get().dispatchEvent(new OnsetEndEvent(onset));
}
onset.end();
}
}
编译器抱怨this(onset, Optional.absent());
说:构造函数 OnsetSequencer(Onset, Optional) 未定义
我试图通过将其更改为this(onset, Optional<EventManager>.absent());
That syntax is wrong 来解决此问题。
我想知道如何解决这个问题!