如何声明方法的泛型类型?

时间:2012-08-17 21:03:57

标签: java generics

我已经为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());来解决此问题 这种语法也是错误的。

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

2 个答案:

答案 0 :(得分:3)

我想你想要:

Optional.<EventManager>absent()

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

答案 1 :(得分:1)

您应该使用:

Optional.<EventManager>absent()