由于Java泛型的实现,您不能拥有这样的代码:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
Run Code Online (Sandbox Code Playgroud)
如何在保持类型安全的同时实现这一点?
我在Java论坛上看到了这样的解决方案:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
Run Code Online (Sandbox Code Playgroud)
但我真的不知道发生了什么.
我正在编写一个将连接到服务器并基于某些参数的类,检索一个json-string,该字符串将使用GSON解析为指定的(通过泛型)类.
这个课程的精简版看起来像这样:
class Executor<T> {
private Response<T> response;
public void execute() {
Type responseType = new TypeToken<Response<T>>() {}.getType();
this.response = new Gson().fromJson(json, responseType);
}
public Response<T> getResponse() { return this.response; }
}
Run Code Online (Sandbox Code Playgroud)
(JSON变量看起来像这样.)
一旦反序列化存储数据的类如下所示:
class Response<T> {
private List<T> data = null;
public List<T> getData() { return this.data; }
}
Run Code Online (Sandbox Code Playgroud)
数据尝试反序列化的类:
public class Language {
public String alias;
public String label;
}
Run Code Online (Sandbox Code Playgroud)
运行的代码使用上面的类:
Executor<Language> executor = new Executor<Language();
List<Language> languages = executor.execute().getResponse().getData();
System.out.println(languages.get(0).alias); // exception occurs …Run Code Online (Sandbox Code Playgroud)