2017-03-15 122 views
0

我試圖從文件加載通過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(); 
      } 
    } 

所以我想搬到一個結構更像 公共類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; 

}} 

但我清楚這裏缺少如何仿製藥應正確使用。

+0

此外...的downvoter ....誰甚至不能被人打擾評論他爲什麼downvoted ...不錯的工作 – Narrim

回答

2

您需要定義泛型類型(<T>)。更改的loadFile簽名:

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

@see Generic Methods

+0

由於工作原理現在預期。 ..我不明白定義和返回類型之間的區別..或者至少了解他們是如何在簽名中單獨聲明的 – Narrim