2013-08-26 90 views
0

我想用Java中的auth系統製作遊戲。當我試圖運行它時,我可以看到控制檯日誌中引發的異常,但是項目中沒有錯誤。我知道這是運行時錯誤關於鑄造的問題

控制檯日誌顯示以下信息:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Auth$Profile 
    at Auth.<init>(Auth.java:30) 

這裏是我的代碼:

public Auth(File profilesFile) { 
       try { 
        ProfilesJSON e = (ProfilesJSON)this.gson.fromJson(new FileReader(profilesFile), ProfilesJSON.class); 
       Map ps = e.authenticationDatabase; 
       Iterator var5 = ps.keySet().iterator(); 

       while(var5.hasNext()) { 
        String name = (String)var5.next(); 
        Profile p = (Profile)ps.get(name); 
        if(p != null) { 
         if(p.displayName == null || p.displayName.length() == 0) { 
          p.displayName = p.username; 
         } 

         this.profiles.add(p); 
        } 
       } 

       } catch (FileNotFoundException var7) { 
       ; 
       } catch (NullPointerException var8) { 
       ; 
       } 
      } 


    public class Profile { 

       public String username; 
       public String password; 
       public String uid; 
       public String displayName; 
       public String name; 
       public String playerUID; 


       public Profile(String u, String t, String id, String d) { 
       this.username = u; 
       this.password = t; 
       this.uid = id; 
       this.displayName = d; 
       } 
      } 

public class ProfilesJSON { 

      public Map profiles; 
      public String selectedProfile; 
      public String password; 
      public Map authenticationDatabase; 


     } 

第30行是:

Profile p = (Profile)ps.get(name); 

這是我的代碼的一部分,我的想法是如果玩家按「記住密碼」,遊戲將生成一個.json文件來存儲他的我nfomation ..我只想知道我做錯了什麼,其他代碼我可以自己寫

+0

* ClassCastException * Java試圖執行強制轉換,但由於沒有繼承而無法執行 –

回答

0

您的ps.get(name)返回一個com.google.gson.internal.LinkedTreeMap對象而不是Profile

嘗試將其更改爲:

LinkedTreeMap p = (LinkedTreeMap)ps.get(name); 

,因爲有一個在編譯時沒有錯誤代碼不告訴你的錯誤,ClassCastException是一個運行時異常。

+0

否...此類從不使用com.google.gson.internal.LinkedTreeMap,如果將我的代碼更改爲您的代碼,則會收到項目錯誤= > p.displayName無法解析,或者不是字段 – Jeremy

+0

@ user2718549肯定存在一個LinkedTreeMap對象,它來自某處。找出。你提到的編譯錯誤是由另一個更改引起的,而不是這個。當然這很明顯? – EJP

+0

@EJP你能幫我解決嗎? – Jeremy