Generics in static methods

ぐ巨炮叔叔 提交于 2019-12-02 02:50:15

You need to pass it.

public static <E extends Thing> E[] parseThingsFromJSON(String body, Class<E[]> eClass) {
    return parser.fromJson(body, eClass);
}

Generics is largely a compile time feature. This means its not available at runtime (with some exceptions)

In this case, to make to make the generic type available at runtime, you have to pass it as an additional argument.

RNJ

From memory this is a similar problem to what you have when using Arrays.asList()

With this you do

Arrays.<MyOjbect>(new MyObject(), new MyObject());

or in your specific case where you are passing an array eg

Arrays.<Integer[]>asList(new Integer[]{new Integer(1)});

The signature in the JDK for this method is

public static <T> List<T> asList(T... a){...}

which is similar to your I think

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!