EdgeCase
EdgeCase

Reputation: 4827

Change This Method to Generic (Without Collection)

I have the following method, which clones an object using gson to do a deep copy. Is there a way to make this method generic, or do generics only pertain to objects that belong to a Collection?

private Order gsonClone(Order t) {
    Gson gson = new Gson();
    String json = gson.toJson(t);
    return gson.fromJson(json, t.getClass());
}

Upvotes: 1

Views: 60

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

You can make any method or class generic by declaring generic parameters. Since you need the class, pass it as a separate parameter:

private <T> T gsonClone(T t, Class<T> type) {
    Gson gson = new Gson();
    String json = gson.toJson(t, type);
    return gson.fromJson(json, type);
}

Upvotes: 3

Related Questions