java为什么这会给我notserializableexception

时间:2013-12-10 19:24:02

标签: java serialization

为什么这会给我一个无法解释的例外?

public class hData implements Serializable {
    String Symbol;
    double Position;

    public hData( String Symbol, double Position){

        this.Symbol = Symbol;
        this.Position = Position;
    }

}


  public List<hData> HData;    

我像这样序列化:

public String objectToString(Serializable object) {
   String encoded = null;

   try {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(object);
    objectOutputStream.close();
    encoded = new String(Base64.encode(byteArrayOutputStream.toByteArray()));
   } catch (IOException e) {
    e.printStackTrace();
   }
   return encoded;
  }

我称之为:

String hd = objectToString((Serializable) HData);

1 个答案:

答案 0 :(得分:0)

我尝试了它并且它有效。这是我保存在hData.java中的代码。 (顺便说一下,按照惯例,Java类是PascalCase,所以,HData是一个更好的类名)

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.sun.org.apache.xml.internal.security.utils.Base64;

public class hData implements Serializable {
    String Symbol;
    double Position;

    public hData( String Symbol, double Position){

        this.Symbol = Symbol;
        this.Position = Position;
    }
    public static String objectToString(Serializable object) {
           String encoded = null;

           try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
            encoded = new String(Base64.encode(byteArrayOutputStream.toByteArray()));
           } catch (IOException e) {
            e.printStackTrace();
           }
           return encoded;
          }
    public static void main(String[] args){
        List<hData> HData = new ArrayList<hData>(); 
        HData.add(new hData("hi", 1.2));
        String hd = objectToString((Serializable) HData);
        System.out.print(hd);
    }
}