开发者

In Java, is it possible to use a type variable, as an array element, inside an Interface?

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

interf开发者_运维技巧ace 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
    }
}


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.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜