我在理解java泛型中的表达式时遇到了一些困难。请在这方面提供帮助:
public interface Inter {
<T extends Enum<T> & FunctionalInterface> String getString();
}
发布于 2018-06-15 08:00:37
您提供的代码是合法的,但无用。
它无用的原因有两个:
Enum<T>
接口和FunctionalInterface
接口。但是,您在方法的签名(即参数或返回类型)中的任何位置都没有使用该类型,因此它实际上被忽略了。你可以让这个组合起作用:
public interface Inter {
<T extends Enum<T> & FunctionalInterface> String getString(T value);
}
static class InterImpl implements Inter {
@Override
public <T extends Enum<T> & FunctionalInterface> String getString(T value) {
return value.name();
}
}
enum EnumImpl implements FunctionalInterface {
A, B, C;
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
}
public static void main(String[] args) {
InterImpl impl = new InterImpl();
System.out.println(impl.getString(EnumImpl.B));
}
您将看到EnumImpl
枚举实现了Enum
和FunctionalInterface
,因此可以将其用作getString
的参数。
这是一种解释,但坦率地说,我想不出这样一段代码有什么有用的用例。
https://stackoverflow.com/questions/50867189
复制相似问题