Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下方法,它使用 gson 克隆对象以进行深层复制。有没有办法使这个方法泛型,或者泛型只与属于集合的对象有关?
private Order gsonClone(Order t) { Gson gson = new Gson(); String json = gson.toJson(t); return gson.fromJson(json, t.getClass()); }
您可以通过声明泛型参数来使任何方法或类成为泛型。由于您需要该类,请将其作为单独的参数传递:
private <T> T gsonClone(T t, Class<T> type) { Gson gson = new Gson(); String json = gson.toJson(t, type); return gson.fromJson(json, type); }