简体   繁体   中英

How does one define a generic wrapper interface type and use it as method return type in java?

I'm trying to do the following: defining a wrapper interface type and have a calculate method that returns that wrapper, but it doesn't work:

public interface Wrapper<T> {
}

public interface Calculator<WrapperType extends Wrapper<?> {
   <T> WrapperType<T> calculate(Supplier<T> calculator);
}

The error is something like "Type Wrapper does not have type parameter". Is this something possible in Java?

This won't compile like this. You can't have this many levels of genericity in java, you're going to have to decide between

public interface Calculator<T> {
   Wrapper<T> calculate(Supplier<T> calculator);
}

and

public interface Calculator<T, WrapperType extends Wrapper<T>> {
   WrapperType calculate(Supplier<T> calculator);
}

The latter gives more flexibility at the cost of an additional complexity.

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