0

我已经为 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 来解决此问题。

我想知道如何解决这个问题!

4

2 回答 2

3

我想你想要:

Optional.<EventManager>absent()

我从不喜欢在 Java 中为泛型方法表达类型参数的方式,但这就是生活。有关详细信息,请参阅JLS 的第 15.12 节

于 2012-08-17T21:06:57.627 回答
1

你应该使用:

Optional.<EventManager>absent()
于 2012-08-17T21:12:00.123 回答