Java泛型,这是最好的方式吗?



下面是我的示例代码

public class Example {
static interface Data {
}
static interface Source<D extends Data> {
public D read();
}
static class Stream<S extends Source<D>, D extends Data> {
public S source;
public Stream(S source){
this.source = source;
}
public D get() {
return this.source.read();
}
}
static class SampleData implements Data {
}
static class SampleSource implements Source<SampleData> {
@Override
public SampleData read() {
return null;
}
}
public static void main(String[] args) {
Stream sampleSourceStream = new Stream<SampleSource, SampleData>();
}
}

我想省略(为了更漂亮的结构/更容易使用)

static class Stream<S extends Source<D>, D extends Data>

static class Stream<S extends Source<D>>

new Stream<SampleSource, SampleData>()

new Stream<SampleSource>()

(我知道它可以在c#中省略…)

我怎样才能省略或做出更漂亮的图案?

不要定义S,它没有任何意义:

static class Stream<D extends Data> {
public Source<D> source;
public Stream(Source<D> source){
this.source = source;
}
public D get() {
return this.source.read();
}
}
public static void main(String[] args) {
SampleSource sampleSource = new SampleSource();
Stream<SampleData> sampleSourceStream = new Stream<>(sampleSource);
}

或者在Java 10+中更简单,使用var:

public static void main(String[] args) {
SampleSource sampleSource = new SampleSource();
var sampleSourceStream = new Stream<>(sampleSource);
}

相关内容

  • 没有找到相关文章

最新更新