简体   繁体   中英

Java generic, Is this best way?

Here is my sample code

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>();
    }
}

I want omit(for more beautiful structure/easy usage)

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

to

static class Stream<S extends Source<D>>

or

new Stream<SampleSource, SampleData>()

to

new Stream<SampleSource>()

(I know it can be omitted in C#...)

How can i omit or make more beautiful pattern?

Don't define S , it serves no purpose:

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);
}

Or even simpler in Java 10+, using var :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM