在Java中,是否可以在接口内部使用类型变量作为数组元素?
在Java中,是否可以在接口内部使用类型变量作为数组元素?
我尝试过作为归档类型和强制转换运算符,但总是收到错误
无法对非静态类型 A 进行静态引用
interface ITest<A> {
A[] j; // Cannot make a static reference to the non-static type A
Object[] = (A[]) new Object[3]; // Cannot make a static reference to the non-static type A
}
在任何情况下,我都可以在接口内(以及枚举类型中?)使用构造 A[]
吗?
class CTest<A> {
enum MyEnum {
F, G, H;
// something that uses A[] inside. Getting the same error as above
}
}
In Java, is it possible to use a type variable, as an array element, inside an Interface?
I've tried as a filed type and as a cast operator, but always get the error
Cannot make a static reference to the non-static type A
interface ITest<A> {
A[] j; // Cannot make a static reference to the non-static type A
Object[] = (A[]) new Object[3]; // Cannot make a static reference to the non-static type A
}
Is there any case, where I am able to use the construct A[]
inside the interface (and in an enum type?)?
class CTest<A> {
enum MyEnum {
F, G, H;
// something that uses A[] inside. Getting the same error as above
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在接口中使用通用数组类型,如下所示:
您的问题是您试图在接口中声明一个字段,除了常量之外,您基本上不能这样做。您不能在接口中声明通用数组类型的字段,但我希望您无论如何也不想这样做。
诚然,类型擦除使得数组和泛型的组合在各种情况下都有些尴尬,但我认为以上至少回答了您提出的问题。
You can use a generic array type in an interface, like this:
Your problem was you were trying to declare a field in an interface, which you basically can't do other than for constants. You can't declare a field of a generic array type in an interface, but I'd hope that you wouldn't want to anyway.
Admittedly type erasure makes the combination of arrays and generics somewhat awkward in various situations, but I think the above at least answers the question you posed.
接口中的字段隐式是公共的、静态的和最终的,它们基本上是常数。并且不能有依赖于类型参数的常量,因为在 Java 中参数会在编译时从类型中删除。
顺便说一句,这与您是否使用数组无关,
也不起作用。也不会
Fields in interfaces are implicitly public, static and final, they're basically constants. And you can't have constants that depend on a type parameter because in Java parameters are removed from the type on compilation.
By the way, this is independent of whether you're using an array or not,
won't work either. And neither would