使用Generic返回从类型

时间:2017-03-15 22:45:46

标签: java generics

我正在尝试从文件中加载由JSON编码的对象..

我每次都可以直接编写内联代码,但我想将保存/加载移动到静态实用程序类,但我不想在主代码中盲目地转换为对象。

所以我目前有

    public Class MyClass(){

    private List<Door> doors;
    private final Type type = new TypeToken<List<Door>>(){}.getType();


    private void load(){
            Gson gsondecoder = new Gson();
            File parent = new File ("saves");
            File file =  new File(parent,"doors.json");
            List<Door> doors= null;
            if (!parent.exists())return;
            if(!file.exists())return;
            try {
                InputStream in = new FileInputStream(file);
                InputStreamReader inread = new InputStreamReader(in);
                JsonReader reader = new JsonReader(inread);
                doors = gsondecoder.fromJson(reader,type);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    }

所以我想转向更像的结构  public Class MyClass(){

    private List<Door> doors;
    private final Type type = new TypeToken<List<Door>>(){}.getType();


    private void load(){
            File parent = new File ("saves");
            File file =  new File(parent,"doors.json");
            List<Door> doors= null;
            doors = (List<door>) Utility.load(file,type);
    }

我的问题是如何在不盲目投降的情况下返回正确的班级 即只是

door = Utility.load(file,type)

我的想法是

public class Utilities {

static Gson gsonencoder = new Gson();
/**
 * The objects class must much the TypeTokens underlying class.
 *
 * @param file
 * @param object
 * @param type
 */
public static void saveFile(File file, T object, TypeToken<T> type) {
    try {
        if (!file.exists()) file.createNewFile();
        OutputStream out = new FileOutputStream(file);
        String encoded = gsonencoder.toJson(object, type.getType());
        out.write(encoded.getBytes());
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static T loadFile(File file, TypeToken<T> type){
    if(!file.exists())return null;
    T object = null;
    try {
        InputStream in = new FileInputStream(file);
        InputStreamReader inread = new InputStreamReader(in);
        JsonReader reader = new JsonReader(inread);
        object = gsonencoder.fromJson(reader,type.getType());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return object;

}}

但我在这里明显缺少如何正确使用泛型。

1 个答案:

答案 0 :(得分:2)

您需要定义泛型类型(&lt; T&gt;)。将loadFile签名更改为:

public static <T> T loadFile(File file, TypeToken<T> type)

@see Generic Methods