0

我想@FunctionalInterface在 Java 中创建一个接受Streams 或Optional类型作为参数的。我试图这样做,但由于它们不共享通用接口,因此似乎无法实现。我还尝试使用调用的通用包装类,@FunctionalInterface但由于我在运行时需要类型参数,所以这似乎是不可能的。

最小示例:

@FunctionalInterface
public interface AcceptingInterface<S, T> {

    T accept(S s);

}

public class Test<S, T> {

    private final AcceptingInterface<S, T> funcInterface;

    private final Class<S> source;

    private final Class<T> target;

    public Test(AcceptingInterface<S, T> a, Class<S> s, Class<T> t) {
        this.funcInterface = a;
        this.source = s;
        this.target = t;
    }

    public T invoke(S s) {
        return s == null ? null : this.funcInterface.accept(s);
    }

    public Class<S> getSource() {
        return source;
    }

    public Class<T> getTarget() {
        return target;
    }
}

也许我的方法是错误的......我很想收到反馈和/或解决这个问题。

4

1 回答 1

4

我假设您想将 Optional 视为 0-1 元素的 Stream,在这种情况下,您可以添加一个从 Optional 转换为 Stream 的默认方法,因此:

@FunctionalInterface
public interface AcceptingInterface<V, T> {

    T accept(Stream<? extends V> s); 
    default T accept(Optional<? extends V> opt){
        return accept(opt.map(Stream::of).orElseGet(Stream::empty)); 
    }

}

Java 9 应该添加一个Optional.stream()方法。

于 2016-07-01T10:04:19.057 回答