简体   繁体   中英

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

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
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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