我为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());
来解决此问题该语法也是错误的。
我想知道如何解决此问题!
最佳答案
我想你要:
Optional.<EventManager>absent()
我从未喜欢过Java中为泛型方法表达类型实参的方式,但这就是生活。有关详细信息,请参见section 15.12 of the JLS。