2016-09-19 1 views
0

"Item"というオブジェクトを作成しましたが、その中にItemを含むArrayListをシリアル化したいとします。私のプログラムは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

定義による直列化は、オブジェクトではなくクラスに適用されます。 転送されるオブジェクトの状態をネットワークやストリーム上にコピーしたり、保存したりします。 静的変数を使用すると、それらはクラス変数になります。したがって、オブジェクトの状態に寄与しません。最初に行うことは、非静的にすることです。

これは、クラスが既にシリアライズ可能であり、それもArrayListです。それらをシリアライズし、ObjectInputStreamとObjectOutputStreamを使用して逆シリアル化することができます。また、クラスのパスがDeserializationエンドで同じクラスになっていることを確認してください。

関連する問題