在Java中,是否可以在接口内部使用类型变量作为数组元素?

发布于 2024-10-13 00:40:35 字数 571 浏览 2 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瀟灑尐姊 2024-10-20 00:40:35

您可以在接口中使用通用数组类型,如下所示:

public interface Foo<T> {
    void doSomething(T[] array);
}

您的问题是您试图在接口中声明一个字段,除了常量之外,您基本上不能这样做。您不能在接口中声明通用数组类型的字段,但我希望您无论如何也不想这样做。

诚然,类型擦除使得数组和泛型的组合在各种情况下都有些尴尬,但我认为以上至少回答了您提出的问题。

You can use a generic array type in an interface, like this:

public interface Foo<T> {
    void doSomething(T[] array);
}

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.

酒解孤独 2024-10-20 00:40:35

接口中的字段隐式是公共的、静态的和最终的,它们基​​本上是常数。并且不能有依赖于类型参数的常量,因为在 Java 中参数会在编译时从类型中删除。

顺便说一句,这与您是否使用数组无关,

public interface X<T> {
    T c = (T)new AnyType();
}

也不起作用。也不会

public class X<T> {
  public static final T c = (T)new AnyType();
}

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,

public interface X<T> {
    T c = (T)new AnyType();
}

won't work either. And neither would

public class X<T> {
  public static final T c = (T)new AnyType();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文