Jannis636
Jannis636

Reputation: 123

Gson "fromJson" with 'T'

I have an class with "T extends StorageClass". You can extend this class and put another class instend of the "T" for example "GroupStorage extends Storage. In the "Storage" class is an method called "get". Now i want that method to convert json to the "T" class, in my case to the "Group" class. Maybe you will understand when you look to the code below.

public abstract class Storage<T extends StorageClass> {
    // This should return whatever T is.
    public T get(String groupName) {
        T t = null;
        File file = new File(this.groupFolderPath, groupName + ".json");
        if (file.exists()) {
            try {
                FileReader reader = new FileReader(file);
                // 'T.class' is not possible
                t = Storage.GSON.fromJson(reader, T.class);
            } catch (Exception e) {
                e.printStackTrace();
                Bukkit.getLogger().warning("Failed to read " + groupName + ".json!");
            }
        } else {
            Bukkit.getLogger().warning("The group " + groupName + " does not exists!");
        }
        return t;
    }
}

Upvotes: 3

Views: 403

Answers (1)

Naman
Naman

Reputation: 31888

You would have to pass down the type of the class to your method as :

public T get(String groupName, Class<T> type)

and then use it as :

t = Storage.GSON.fromJson(reader, type);

Upvotes: 1

Related Questions