[英]Is it possible to have a Type Parameter that extends 2 other type parameters?
Here is my goal: I want to have an argument that needs to be two separate types at the same time.这是我的目标:我想要一个需要同时为两种不同类型的参数。
The goal here is to extract two different types from a single object using just generics (no casting or instanceof
).这里的目标是仅使用泛型(无强制转换或instanceof
)从单个对象中提取两种不同的类型。
My idea is to have a third type parameter that extends
the other two.我的想法是有第三个类型参数来extends
其他两个。
class DualType<A, B> {
A a;
B b;
<T extends A & B> DualType(T obj) {
a = obj;
b = obj;
}
}
This does not work.这不起作用。 Since java does not support multiple inheritance, and there isn't a way the compiler can guarantee that B isn't another class, we get an error.由于 java 不支持多重继承,并且编译器无法保证 B 不是另一个类,所以我们得到一个错误。
My question is this: Is there some way to define a type parameter that constrains it to only be used with interfaces?我的问题是:有没有办法定义一个类型参数来限制它只与接口一起使用? I would assume you would be able to use implements
rather than extends
but as we all know, only super
and extends
are valid in type parameter declarations.我假设您可以使用implements
而不是extends
,但众所周知,只有super
和extends
在类型参数声明中有效。 Is there a workaround for this?有解决方法吗? Or is it simply not possible?还是根本不可能?
The thing I am trying to achieve here isn't for some practical purpose, but I rather would just like to know if something like this is possible at all in Java?我在这里尝试实现的目标不是出于某种实际目的,而是我只想知道在 Java 中是否可以实现这样的事情?
Is there some way to define a type parameter that constrains it to only be used with interfaces?有什么方法可以定义一个类型参数,将其限制为仅与接口一起使用?
Compiler can't know whether A
and B
are interfaces or classes, since these type variables are only placeholders and actual types will be provided at runtime.编译器无法知道A
和B
是接口还是类,因为这些类型变量只是占位符,实际类型将在运行时提供。
And since type variable T
has multiple bounds <T extends A & B>
only A
can be a class and B
should be an interface.由于类型变量T
有多个界限<T extends A & B>
只有A
可以是一个类, B
应该是一个接口。 But B
can be pretty much anything, and therefore your constructor causes a compilation error.但是B
几乎可以是任何东西,因此您的构造函数会导致编译错误。
only "super" and "extends" are valid in type parameter declarations只有“super”和“extends”在类型参数声明中有效
That's not correct.这是不正确的。 We can use super
only with wild cards, not with bounded types.我们只能将super
与通配符一起使用,而不能与有界类型一起使用。 T super MyInterface
will not compile. T super MyInterface
不会编译。 With bounded type parameters we can use only extends
.对于有界类型参数,我们只能使用extends
。
And it's not possible to let the compiler know that B
is an interface by using extends
.并且不可能通过使用extends
让编译器知道B
是一个接口。 Even if bound would be an interface B extends MyInterface
it doesn't imply that B
expected to be an interface.即使 bound 是一个接口B extends MyInterface
它并不意味着B
应该是一个接口。
There's no way to achieve what you're trying to do.没有办法实现你想要做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.