2016-09-19 69 views
0

我已經創建了一個名爲「Item」的對象,我想用序列化一個ArrayList裏面的Items。我的程序完美適用於ArrayList<String>,但它不適用於ArrayList<Item>。我相信這與我的對象有關。這是它:序列化Arraylist <CustomObject>

public class Item implements Serializable{ 

private static String name; 
private static BufferedImage picture; 
private static boolean craftable; 
private static Item[][] craftTable; 
private static boolean smeltable; 
private static Item smelt_ancestor; 
private static Item smelt_descendant; 

public Item(String name, boolean craftable, boolean smeltable){ 
    this.name = name; 
    this.craftable = craftable; 
    if(craftable){ 
     craftTable = new Item[3][3]; 
    }else{ 
     craftTable = null; 
    } 
    this.picture = null; 
    this.smeltable = smeltable; 
    this.smelt_ancestor = null; 
    this.smelt_descendant = null; 
} 

public String getName(){ 
    return name; 
} 

public void setName(String name){ 
    this.name=name; 
} 

public BufferedImage getPicture(){ 
    return picture; 
} 

public boolean setPicture(){ 
    boolean verify = false; 
    String pictureName = name.replaceAll("\\s+",""); 
    String newNamePng = pictureName + ".png"; 
    String newNameJpg = pictureName + ".jpg"; 
    File imagePng = new File(newNamePng); 
    File imageJpg = new File(newNameJpg); 
    if(imagePng.exists()){ 
     return true; 
    }else if(imageJpg.exists()){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

public boolean getCraftable(){ 
    return craftable; 
} 

public void setCraftable(boolean value){ 

    this.craftable = value; 
} 

public boolean setCraftTable(Item[][] table){ 
    if(this.craftable==true){ 
     craftTable = table; 
     return true; 
    }else{ 
     return false; 
    } 

} 

public Item[][] getCraftTable(){ 
    return craftTable; 
} 

public boolean getSmeltable(){ 
    return smeltable; 
} 

public void setSmeltable(boolean value){ 
    smeltable = value; 
} 

public Item getAncestor(){ 
    return smelt_ancestor; 
} 

public void setAncestor(Item ancestor){ 
    smelt_ancestor = ancestor; 
} 

public Item getDescendant(){ 
    return smelt_descendant; 
} 

public void setDescendant(Item des){ 
    smelt_descendant = des; 
} 

public String toString(){ 
    return name; 
} 

忽略進口,我用他們在其他方法我省略,因爲他們工作完美。對象有什麼問題可以阻止它被正確序列化?

+3

所有的字段都是靜態的。瞭解這意味着什麼。這是沒有意義的。 https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html –

回答

2

靜態變量不會被序列化。它看起來像你可能希望那些是非靜態的實例變量。

+0

你是對的,謝謝!我仍然在學習:D –

0

按定義的序列化應用於對象而不是類。 它複製要通過網絡或流傳輸或要存儲的對象的狀態。 您對靜態變量的使用使它們成爲類變量,因此它們不會影響對象的狀態。首先要做的就是讓它們變成非靜態的。

這給我們留下了你的類,它已經是Serializable了,ArrayList也是如此。您可以使用ObjectInputStream和ObjectOutputStream對它們進行序列化和反序列化,並確保在反序列化結束時在類路徑中具有相同的類。