简体   繁体   English

创建一个具有可变数量的泛型类型的类

[英]Create a class with a variable number of generic type

I would like to create a class that can handle an undefined number of generic type is that even possible with java ?我想创建一个可以处理未定义数量的泛型类型的类,甚至可以使用 java 吗?

The idea behind this weird question is to create a tuple with a size fixed in his contructor where each element at position i is of the type at the pos i%numberoftype .这个奇怪问题背后的想法是创建一个大小固定在他的构造函数中的元组,其中位置i每个元素都是 pos i%numberoftype的类型。

No, types in Java have a fixed number of type parameters.不,Java 中的类型具有固定数量的类型参数。

The closest you could get is to have a (finite) number of related classes:您可以获得的最接近的是拥有(有限)数量的相关类:

class Tuple1<A> { ... }

class Tuple2<A, B> { ... }

class Tuple3<A, B, C> { ... }

And then provide a common class with factory methods:然后提供一个带有工厂方法的公共类:

class Tuples {
  static <A> Tuple1<A> of(A a) { ... }
  static <A, B> Tuple2<A,B> of(A a, B b) { ... }
  static <A, B, C> Tuple1<A,B,C> of(A a, B b, C c) { ... }
}

As Joachim says, Java generic types have a fixed number of type parameters.正如 Joachim 所说,Java 泛型类型具有固定数量的类型参数。 A variable number is not supported.不支持变量编号。

AFAIK, the JLS doesn't state this explicitly, but the Java syntax for a generic class only allows declarations with a fixed number of parameters. AFAIK,JLS 没有明确说明这一点,但是泛型类的 Java 语法只允许使用固定数量的参数进行声明。

See JLS 8.1.2 gives the grammar rules as:参见JLS 8.1.2给出的语法规则为:

TypeParameters    ::= '<' TypeParameterList '>'
TypeParameterList ::= TypeParameter { ',' TypeParameter }

(I have tweaked meta-syntax to distinguish language symbols meta-symbols.) (我已经调整了元语法以区分语言符号元符号。)


I am not aware of any main-stream programming language that supports generic / parameterized types with a variable number of type parameters.我不知道任何支持具有可变数量类型参数的泛型/参数化类型的主流编程语言。 I suspect that type-checking such a language (if it existed) would be challenging.我怀疑对这种语言(如果存在)进行类型检查将具有挑战性。 And, I doubt that there would be many legitimate use-cases for such a language feature.而且,我怀疑这样的语言功能会有很多合法的用例。 (But perhaps that's just my lack of imagination ...) (但也许那只是我缺乏想象力......)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM