从扩展通用中提取泛型类型 [英] Extract Generic types from extended Generic
问题描述
我试图重构一个类和一组M类扩展任何类的子类,即使我们知道它必须是某种类型的子类。该类型是参数化的,我希望它的参数化类型可用于已经具有M值的子类。
有没有什么办法可以定义这个类而不必包含参数列表中冗余的K和V泛型类型。我希望能够让编译器从任何M被子类映射到的地方推断出它们。
public abstract class NewParametrized< ; K,V,M延伸SomeParametrized< K,V>> {
public void someMethodThatTakesKAndV(K k1,V v1){}
}
换句话说,我希望类声明看起来像这样:
public class NewParametrized< M扩展SomeParametrized< K,V>> {
K和V的类型可以从M的定义中推断出来。
问题在于 K
和 V
并没有真正的重复,至少没有比变量声明和对同一变量的使用是重复。
想法这是你声明泛型类型 K
和 V
,然后在定义中使用那些声明的泛型类型泛型类型 M
。因此,您不要多次声明泛型类型 K
或 V
:相反,您声明每个类型一次,然后在别的声明中引用它们。
换一种方式来看,这里泛型类型的数量仍然是三个,即 K
, V
和 M
。 M
碰巧用 K
和 V
,但你不必定义 M
。
我应该补充说,如果您是类型推断的支持者,您可以查看声明并使用相同的变量作为不必要的重复。但是,如果您习惯使用Java编程(或C或C ++或许多其他语言),那么您可能习惯于在使用它们之前声明变量。
I'm trying to refactor a class and set of subclasses where the M type does extend anything, even though we know it has to be a subclass of a certain type. That type is parametrized and I would like its parametrized types to be available to subclasses that already have values for M.
Is there any way to define this class without having to include the redundant K and V generic types in the parameter list. I'd like to be able to have the compiler infer them from whatever M is mapped to by subclasses.
public abstract class NewParametrized<K, V, M extends SomeParametrized<K, V>> {
public void someMethodThatTakesKAndV(K k1, V v1) { }
}
In other words, I'd like the class declaration to look something like:
public class NewParametrized<M extends SomeParametrized<K, V>> {
And K and V's types would be inferred from the definition of M.
The problem is that K
and V
aren't really "repeated", at least not any more than a variable declaration and a use of that same variable are "repetition".
The way to think of this is that you declare the generic types K
and V
, and then you use those declared generic types in the definition of the generic type M
. So, you don't declare the generic type K
or V
more than once: Rather, you declare each of them once and then refer to them in a declaration of something else.
To look at it another way, the number of generic types here is still three, namely K
, V
, and M
. M
happens to be defined in terms of K
and V
, but you didn't have to define M
that way.
I should add that if you are a proponent of type inference, you might view the declaration and the use of the same variable as unnecessary repetition. However, if you're accustomed to programming in Java (or C, or C++, or many, many other languages), then you're probably accustomed to declaring variables before you use them.
这篇关于从扩展通用中提取泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!