Java泛型&;操作人员
我在理解java泛型中的表达式时遇到了一些困难。 请在此方面提供帮助:Java泛型&;操作人员,java,generics,Java,Generics,我在理解java泛型中的表达式时遇到了一些困难。 请在此方面提供帮助: public interface Inter { <T extends Enum<T> & FunctionalInterface> String getString(); } 公共接口{ 字符串getString(); } 您提供的代码是合法的,但没有用处 这是无用的,原因有二: 您已经定义了泛型类型T,作为方法声明的一部分,它必须实现Enum接口以及functional接口。但是
public interface Inter {
<T extends Enum<T> & FunctionalInterface> String getString();
}
公共接口{
字符串getString();
}
您提供的代码是合法的,但没有用处
这是无用的,原因有二:
Enum
接口以及functional接口。但是,您没有在方法签名的任何地方使用该类型(即参数或返回类型),因此它实际上被忽略
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));
}
公共接口{
字符串getString(T值);
}
静态类InterImpl实现InterImpl{
@凌驾
公共字符串getString(T值){
返回值.name();
}
}
enum EnumImpl实现功能接口{
A、 B,C;
@凌驾
public Class您提供的代码是合法的,但没有用处
这是无用的,原因有二:
您已经定义了泛型类型T,作为方法声明的一部分,它必须实现Enum
接口以及functioninterface
接口。但是,您没有在方法签名的任何位置使用该类型(即参数或返回类型),因此它实际上被忽略
有一个接口实现“FunctionInterface”是可能的,但肯定不是它的预期用途。它被设计为接口的注释,而不是接口本身
您可以使这种组合起作用:
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));
}
公共接口{
字符串getString(T值);
}
静态类InterImpl实现InterImpl{
@凌驾
公共字符串getString(T值){
返回值.name();
}
}
enum EnumImpl实现功能接口{
A、 B,C;
@凌驾
public ClassIt看起来像是类型参数T
的无用声明。感谢TargetMan的响应。老实说,我想知道此表达式中的含义及其工作原理。它表示交叉点类型。感谢Jacob G的回答。如果可能的话,您可以告诉我交叉点类型的实际用法。非常感谢。它看起来就像一个无用的类型参数声明T
。感谢RGETMAN的响应。老实说,我想知道这个表达式中的&是什么意思以及它是如何工作的。它代表一个交叉点类型。感谢Jacob G的回答。如果可能的话,你能告诉我交叉点类型的实际用法吗。非常感谢。