Java 如何判断对象是可序列化的还是不可序列化的?

Java 如何判断对象是可序列化的还是不可序列化的?,java,oop,serialization,data-structures,deserialization,Java,Oop,Serialization,Data Structures,Deserialization,假设我们想在另一个列表中存储一些列表。我们根据用户要求处理我们的列表。有些列表已排序,有些则未排序。要对列表进行排序,我们使用排序算法。现在,当用户关闭程序时,已排序的工作将丢失。我们希望通过序列化来保存此工作。 有些对象是可序列化的,有些则不是 run: Draft1 java.io.NotSerializableException: drafts.Drafts ..\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (to

假设我们想在另一个列表中存储一些列表。我们根据用户要求处理我们的列表。有些列表已排序,有些则未排序。要对列表进行排序,我们使用排序算法。现在,当用户关闭程序时,已排序的工作将丢失。我们希望通过序列化来保存此工作。 有些对象是可序列化的,有些则不是

run:
Draft1 java.io.NotSerializableException: drafts.Drafts
..\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
这里发生了什么事

  • 我们从课堂草稿开始
  • 我们将其更改为类Drafts implements Serializable
  • 我们想使用一个外部类
  • 我们无法控制阶级虚构,我们无法序列化它,或者当我们尝试时它会给我们错误
  • 所以我们把它改成了私人小说
如何判断对象是否可序列化? 不使用破坏性测试。

/*
 * Drafts.java
 */
package drafts;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Drafts
 */
public class Drafts implements Serializable{
    private int id;
    private String title;
    private boolean hardCopy;
    private String author; 
    private String discription; 
    private int year;
    private List<String> unsortedList;
    private List<String> sortedList;
    private List<List<String>> myList;
    private List<Drafts> draftList;
    private List<Object> objList;
    private List<Fiction> fictionList;
    private Map<Integer, List<String>> recentFiles;
    private transient int last;
    private Drafts lastDrafts;
    //private Fiction lastFiction;
    private transient Fiction lastFiction;
    private boolean lastb;
    private Date timeb;

    public Drafts(int i, String tl, boolean hc, String au, String dis, int yr) {
        id = i;
        title = tl;
        hardCopy = hc;
        author = au; 
        discription = dis; 
        year = yr;
        unsortedList = new ArrayList<>();
        sortedList = new ArrayList<>();
        myList = new ArrayList<>();
        draftList = new ArrayList<>();
        recentFiles = new HashMap<>();
        objList = new ArrayList<>();
        fictionList = new ArrayList<>();
        last = 0;
        lastb = true;
        timeb = new Date();
        objList.add(id);
        objList.add(timeb);
        objList.add(author);
        objList.add(title);
    }

    public Drafts(){
        lastDrafts = newDrafts();
        objList = new ArrayList<>();
        fictionList = new ArrayList<>();
    }

    private Drafts newDrafts(){
        // deserialize the Drafts
        Drafts lastBooks = null;
        lastb = true;
        try {
            FileInputStream fi = new FileInputStream("tmp");
            ObjectInputStream si = new ObjectInputStream(fi);
            lastBooks = (Drafts) si.readObject();
        }catch (Exception e) {
            System.out.println("Draft02 "+e);
            lastb = false;
            //System.exit(1);
        }

        return lastBooks;
    }

    private void saveDrafts(Drafts book){
        // serialize the Drafts
        try {
            FileOutputStream fo = new FileOutputStream("tmp");
            ObjectOutputStream so = new ObjectOutputStream(fo);
            so.writeObject(book);
            so.flush();
        } catch (Exception e) {
            System.out.println("Draft01 "+e);
            System.exit(1);
        }
    }

    public void update(String d) {
        unsortedList.add(d);
        objList.add(d);
        sortBlist(d);
        recentFiles.put(last, myList.get(myList.size() - 1));
        last++;
    }

    private void saveFiction(Fiction lastf){
        lastFiction = lastf;
        //objList.add(lastFiction);
        //fictionList.add(lastf);
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //Draft02 java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: drafts.Fiction
        //Draft01 java.io.NotSerializableException: drafts.Fiction
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

    private void sortBlist(String d){
        //Sort and add to sorted.
        sortedList.add(d);
        myList.add(sortedList);
        objList.add(sortedList);
        sortedList = new ArrayList<>();
    }

    private int searchBlist(String xText, String yText, List<String> sList, int beg, int end){
        //Search x in sList and replace it with y.
        //boolean found = false;
        //int n = -1;
        return 0;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long t0 = System.currentTimeMillis();
        // create a Drafts object
        Drafts Test = new Drafts();
        Drafts book = new Drafts(100, "Functional programming", true, "S.P", "Programming", 2016);
        Drafts book1 = new Drafts(200, "Object OP", true, "O.S", "Data Structures", 2017);
        Drafts book2 = new Drafts(300, "How to deserialize", true, "D.D", "Deserialization", 2018);
        Drafts bookD = null;
        //
        Fiction book3 = new Fiction(100, "Virtual space.", "R.P", 2000);
        book.saveFiction(book3);
        book.update(book.lastFiction.getTitle());
        //
        String bookN0 = t0+"#1 Searching for an answer on the web is like searching a "
                + "needle on a haystack. Probably there is an answer for "
                + "everything. If there is non or we can't find one, then "
                + "we can create one. The old saying was, if it is not broken "
                + "don't fix it! The brand new one is, if it is not perfect "
                + "keep on trying!";

        book.update(bookN0);
        book1.update(bookN0);
        book2.update(bookN0);
        t0 = System.currentTimeMillis();

        String bookN1 = t0+"#2 Some array types containing other array types might not "
                + "deserialize correctly, as all elements of the child type "
                + "will point to the same memory. This limitation may be "
                + "addressed in the future.";

        book.update(bookN1);
        book1.update(bookN1);
        t0 = System.currentTimeMillis();
        String bookN2 = t0+"#3 1234567890...";
        book2.update(bookN2);

        book.draftList.add(book);
        book.draftList.add(book1);
        book.draftList.add(book2);
        book.myList.add(book2.unsortedList);

        // serialize the Drafts
        book.saveDrafts(book);

        // deserialize the Drafts
        bookD = book.newDrafts();

        System.out.println();
        System.out.println("////////draft...");
        System.out.println("Original: "+book);
        System.out.println("Original: "+book.id);
        System.out.println("Original: "+book.last);
        System.out.println("//////////draftD... ");
        System.out.println("Deserialize: "+bookD);
        System.out.println("Deserialize: "+bookD.id);
        System.out.println("Deserialize: "+bookD.last);
        System.out.println(bookD.unsortedList.size());
        System.out.println(bookD.unsortedList.get(0));
        System.out.println(bookD.draftList.get(0).title);
        System.out.println(bookD.draftList.get(1).title);
        System.out.println("/////////////List Des");
        System.out.println("objList size: "+bookD.objList.size());
        System.out.println("objList: "+bookD.objList);
        System.out.println("S1: "+bookD.myList.size());
        System.out.println("S2a: "+bookD.myList.get(0));
        System.out.println("S2b: "+bookD.myList.get(1));
        System.out.println("S2c: "+bookD.myList.get(2));
        System.out.println("S2d: "+bookD.myList.get(3));
        System.out.println("S3: "+bookD.myList.get(0).get(0));
        System.out.println("S4: "+bookD.myList.get(1).get(0));
        System.out.println("S4a: "+bookD.myList.get(2).get(0));
        System.out.println("S4b: "+bookD.myList.get(3).get(0));
        System.out.println("S4c: "+bookD.myList.get(3).get(1));
        System.out.println("S4d: "+bookD.myList);
        System.out.println("S5: "+bookD.recentFiles.toString());
        System.out.println("S6: "+bookD.recentFiles.get(1));
        System.out.println("S7: "+bookD.recentFiles.get(0));
        System.out.println("S8: "+bookD.timeb);
        System.out.println("//////////TestD... ");
        if(Test.lastb){
            System.out.println("TS1: "+Test.lastDrafts.myList.size());
            System.out.println("TS2a: "+Test.lastDrafts.myList.get(0));
            System.out.println("TS2b: "+Test.lastDrafts.myList.get(1));
            System.out.println("TS2c: "+Test.lastDrafts.myList.get(2));
            System.out.println("TS3: "+Test.lastDrafts.myList.get(0).get(0));
            System.out.println("TS4: "+Test.lastDrafts.myList.get(1).get(0));
            System.out.println("TS4a: "+Test.lastDrafts.myList.get(3).get(1));
            System.out.println("TS5: "+Test.lastDrafts.recentFiles.toString());
            System.out.println("TS6: "+Test.lastDrafts.recentFiles.get(1));
            System.out.println("TS7: "+Test.lastDrafts.recentFiles.get(0));
            System.out.println("TS8: "+Test.lastDrafts.timeb);
        }
        else{
            System.out.println("//////////TestD... "+Test.lastb);
        }
        System.out.println();
    }   
}
/*
*Drafts.java
*/
一揽子草案;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.ObjectInputStream;
导入java.io.ObjectOutputStream;
导入java.io.Serializable;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
/**
*
*@草稿
*/
公共类草稿实现可序列化{
私有int-id;
私有字符串标题;
私人印刷版;
私有字符串作者;
私有字符串描述;
私人国际年;
私有列表未分类列表;
私人名单;
私人名单;
私人名单草拟名单;
私有列表对象列表;
私人名单;
私有地图接收文件;
私密的暂时的最后;
私人汇票;
//私人小说;
私人临时小说;
私有布尔lastb;
私人约会时间b;
公共草稿(整数i、字符串tl、布尔hc、字符串au、字符串dis、整数yr){
id=i;
title=tl;
硬拷贝=hc;
作者=au;
描述=dis;
年=年;
unsortedList=newarraylist();
sortedList=新的ArrayList();
myList=新的ArrayList();
draftList=新的ArrayList();
recentFiles=newhashmap();
objList=newarraylist();
虚构列表=新的ArrayList();
last=0;
lastb=真;
timeb=新日期();
对象列表添加(id);
对象列表添加(timeb);
添加(作者);
对象列表添加(标题);
}
公开草稿(){
lastDrafts=newDrafts();
objList=newarraylist();
虚构列表=新的ArrayList();
}
私人汇票{
//反序列化草稿
草稿lastBooks=null;
lastb=真;
试一试{
FileInputStream fi=新的FileInputStream(“tmp”);
ObjectInputStream si=新ObjectInputStream(fi);
lastBooks=(草稿)si.readObject();
}捕获(例外e){
系统输出打印项次(“Draft02”+e);
lastb=假;
//系统出口(1);
}
归还新书;
}
私人作废保存草稿(草稿簿){
//将草稿序列化
试一试{
FileOutputStream fo=新的FileOutputStream(“tmp”);
ObjectOutputStream so=新的ObjectOutputStream(fo);
所以,写对象(书);
所以,flush();
}捕获(例外e){
系统输出打印项次(“Draft01”+e);
系统出口(1);
}
}
公共无效更新(字符串d){
未分类列表。添加(d);
对象列表添加(d);
分类表(d);
recentFiles.put(最后一个,myList.get(myList.size()-1));
last++;
}
私人小说(小说lastf){
LastFrient=lastf;
//添加(最新小说);
//添加(lastf);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Draft02 java.io.WriteableOrtedException:写入中止;java.io.NotSerializableException:drafts.虚构
//Draft01 java.io.NotSerializableException:drafts.虚构
////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
私有无效排序列表(字符串d){
//排序并添加到已排序的。
分类列表。添加(d);
myList.add(分类列表);
对象列表。添加(分类列表);
sortedList=新的ArrayList();
}
私有整数搜索列表(字符串xText、字符串yText、列表sList、整数beg、整数end){
//在sList中搜索x并将其替换为y。
//布尔值=false;
//int n=-1;
返回0;
}
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
长t0=System.currentTimeMillis();
//创建草稿对象
草稿测试=新草稿();
草稿簿=新草稿(100,“函数式编程”,真实,“S.P”,“编程”,2016);
草案1=新草案(200,“对象操作”,真实,“O.S”,“数据结构”,2017年);
草稿书籍2=新草稿(300,“如何反序列化”,正确,“D.D”,“反序列化”,2018年);
草稿簿记d=null;
//
小说书籍3=新小说(100,《虚拟空间》,《R.P》,2000年);
《拯救小说》(第三册);
book.update(book.lastFrience.getTitle());
//
字符串bookN0=t0+“#1在web上搜索答案就像搜索
+“大海捞针,也许有答案”
+“一切。如果没有,或者我们找不到,那么”
+“我们可以创造一个。俗话说,如果它不被打破”
+“别修好它!如果它不完美,那就是全新的”
+“继续尝试!”;
图书更新(bookN0);
book1.更新(bookN0);
book2.更新(bookN0);
t0=系统电流
run:
////////draft...
Original: drafts.Drafts@6d03e736
Original: 100
Original: 3
//////////draftD... 
Deserialize: drafts.Drafts@17a7cec2
Deserialize: 100
Deserialize: 0
3
Virtual space.
Functional programming
Object OP
/////////////List Des
S1: 4
S2a: [Virtual space.]
S2b: [1569099619496#1 Searching for an answer on the web is like searching a needle on a haystack. Probably there is an answer for everything. If there is non or we can't find one, then we can create one. The old saying was, if it is not broken don't fix it! The brand new one is, if it is not perfect keep on trying!]
//.....................................................................//
TS4a: 1569099166372#3 1234567890...
TS5: {0=[Virtual space.], 1=[1569099166091#1 Searching for an answer on the web is like searching a needle on a haystack. Probably there is an answer for everything. If there is non or we can't find one, then we can create one. The old saying was, if it is not broken don't fix it! The brand new one is, if it is not perfect keep on trying!], 2=[1569099166372#2 Some array types containing other array types might not deserialize correctly, as all elements of the child type will point to the same memory. This limitation may be addressed in the future.]}
TS6: [1569099166091#1 Searching for an answer on the web is like searching a needle on a haystack. Probably there is an answer for everything. If there is non or we can't find one, then we can create one. The old saying was, if it is not broken don't fix it! The brand new one is, if it is not perfect keep on trying!]
TS7: [Virtual space.]
TS8: Sat Sep 21 22:52:46 CAT 2019
BUILD SUCCESSFUL (total time: 1 second)
/*
 * Drafts.java
 */
package drafts;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Drafts
 */
public class Drafts implements Serializable{
    private int id;
    private String title;
    private boolean hardCopy;
    private String author; 
    private String discription; 
    private int year;
    private List<String> unsortedList;
    private List<String> sortedList;
    private List<List<String>> myList;
    private List<Drafts> draftList;
    private List<Object> objList;
    private List<Fiction> fictionList;
    private Map<Integer, List<String>> recentFiles;
    private transient int last;
    private Drafts lastDrafts;
    //private Fiction lastFiction;
    private transient Fiction lastFiction;
    private boolean lastb;
    private Date timeb;

    public Drafts(int i, String tl, boolean hc, String au, String dis, int yr) {
        id = i;
        title = tl;
        hardCopy = hc;
        author = au; 
        discription = dis; 
        year = yr;
        unsortedList = new ArrayList<>();
        sortedList = new ArrayList<>();
        myList = new ArrayList<>();
        draftList = new ArrayList<>();
        recentFiles = new HashMap<>();
        objList = new ArrayList<>();
        fictionList = new ArrayList<>();
        last = 0;
        lastb = true;
        timeb = new Date();
        objList.add(id);
        objList.add(timeb);
        objList.add(author);
        objList.add(title);
    }

    public Drafts(){
        lastDrafts = newDrafts();
        objList = new ArrayList<>();
        fictionList = new ArrayList<>();
    }

    private Drafts newDrafts(){
        // deserialize the Drafts
        Drafts lastBooks = null;
        lastb = true;
        try {
            FileInputStream fi = new FileInputStream("tmp");
            ObjectInputStream si = new ObjectInputStream(fi);
            lastBooks = (Drafts) si.readObject();
        }catch (Exception e) {
            System.out.println("Draft02 "+e);
            lastb = false;
            //System.exit(1);
        }

        return lastBooks;
    }

    private void saveDrafts(Drafts book){
        // serialize the Drafts
        try {
            FileOutputStream fo = new FileOutputStream("tmp");
            ObjectOutputStream so = new ObjectOutputStream(fo);
            so.writeObject(book);
            so.flush();
        } catch (Exception e) {
            System.out.println("Draft01 "+e);
            System.exit(1);
        }
    }

    public void update(String d) {
        unsortedList.add(d);
        objList.add(d);
        sortBlist(d);
        recentFiles.put(last, myList.get(myList.size() - 1));
        last++;
    }

    private void saveFiction(Fiction lastf){
        lastFiction = lastf;
        //objList.add(lastFiction);
        //fictionList.add(lastf);
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //Draft02 java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: drafts.Fiction
        //Draft01 java.io.NotSerializableException: drafts.Fiction
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

    private void sortBlist(String d){
        //Sort and add to sorted.
        sortedList.add(d);
        myList.add(sortedList);
        objList.add(sortedList);
        sortedList = new ArrayList<>();
    }

    private int searchBlist(String xText, String yText, List<String> sList, int beg, int end){
        //Search x in sList and replace it with y.
        //boolean found = false;
        //int n = -1;
        return 0;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        long t0 = System.currentTimeMillis();
        // create a Drafts object
        Drafts Test = new Drafts();
        Drafts book = new Drafts(100, "Functional programming", true, "S.P", "Programming", 2016);
        Drafts book1 = new Drafts(200, "Object OP", true, "O.S", "Data Structures", 2017);
        Drafts book2 = new Drafts(300, "How to deserialize", true, "D.D", "Deserialization", 2018);
        Drafts bookD = null;
        //
        Fiction book3 = new Fiction(100, "Virtual space.", "R.P", 2000);
        book.saveFiction(book3);
        book.update(book.lastFiction.getTitle());
        //
        String bookN0 = t0+"#1 Searching for an answer on the web is like searching a "
                + "needle on a haystack. Probably there is an answer for "
                + "everything. If there is non or we can't find one, then "
                + "we can create one. The old saying was, if it is not broken "
                + "don't fix it! The brand new one is, if it is not perfect "
                + "keep on trying!";

        book.update(bookN0);
        book1.update(bookN0);
        book2.update(bookN0);
        t0 = System.currentTimeMillis();

        String bookN1 = t0+"#2 Some array types containing other array types might not "
                + "deserialize correctly, as all elements of the child type "
                + "will point to the same memory. This limitation may be "
                + "addressed in the future.";

        book.update(bookN1);
        book1.update(bookN1);
        t0 = System.currentTimeMillis();
        String bookN2 = t0+"#3 1234567890...";
        book2.update(bookN2);

        book.draftList.add(book);
        book.draftList.add(book1);
        book.draftList.add(book2);
        book.myList.add(book2.unsortedList);

        // serialize the Drafts
        book.saveDrafts(book);

        // deserialize the Drafts
        bookD = book.newDrafts();

        System.out.println();
        System.out.println("////////draft...");
        System.out.println("Original: "+book);
        System.out.println("Original: "+book.id);
        System.out.println("Original: "+book.last);
        System.out.println("//////////draftD... ");
        System.out.println("Deserialize: "+bookD);
        System.out.println("Deserialize: "+bookD.id);
        System.out.println("Deserialize: "+bookD.last);
        System.out.println(bookD.unsortedList.size());
        System.out.println(bookD.unsortedList.get(0));
        System.out.println(bookD.draftList.get(0).title);
        System.out.println(bookD.draftList.get(1).title);
        System.out.println("/////////////List Des");
        System.out.println("objList size: "+bookD.objList.size());
        System.out.println("objList: "+bookD.objList);
        System.out.println("S1: "+bookD.myList.size());
        System.out.println("S2a: "+bookD.myList.get(0));
        System.out.println("S2b: "+bookD.myList.get(1));
        System.out.println("S2c: "+bookD.myList.get(2));
        System.out.println("S2d: "+bookD.myList.get(3));
        System.out.println("S3: "+bookD.myList.get(0).get(0));
        System.out.println("S4: "+bookD.myList.get(1).get(0));
        System.out.println("S4a: "+bookD.myList.get(2).get(0));
        System.out.println("S4b: "+bookD.myList.get(3).get(0));
        System.out.println("S4c: "+bookD.myList.get(3).get(1));
        System.out.println("S4d: "+bookD.myList);
        System.out.println("S5: "+bookD.recentFiles.toString());
        System.out.println("S6: "+bookD.recentFiles.get(1));
        System.out.println("S7: "+bookD.recentFiles.get(0));
        System.out.println("S8: "+bookD.timeb);
        System.out.println("//////////TestD... ");
        if(Test.lastb){
            System.out.println("TS1: "+Test.lastDrafts.myList.size());
            System.out.println("TS2a: "+Test.lastDrafts.myList.get(0));
            System.out.println("TS2b: "+Test.lastDrafts.myList.get(1));
            System.out.println("TS2c: "+Test.lastDrafts.myList.get(2));
            System.out.println("TS3: "+Test.lastDrafts.myList.get(0).get(0));
            System.out.println("TS4: "+Test.lastDrafts.myList.get(1).get(0));
            System.out.println("TS4a: "+Test.lastDrafts.myList.get(3).get(1));
            System.out.println("TS5: "+Test.lastDrafts.recentFiles.toString());
            System.out.println("TS6: "+Test.lastDrafts.recentFiles.get(1));
            System.out.println("TS7: "+Test.lastDrafts.recentFiles.get(0));
            System.out.println("TS8: "+Test.lastDrafts.timeb);
        }
        else{
            System.out.println("//////////TestD... "+Test.lastb);
        }
        System.out.println();
    }   
}
private void saveDrafts(Drafts book){
    // serialize the Drafts
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(new File("tmp/draft.json"), book);
    } catch (Exception e) {
        System.out.println("Draft01 "+e);
        System.exit(1);
    }
}
private Drafts readDrafts(){
    // serialize the Drafts
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new File("tmp/draft.json"), Drafts.class);
    } catch (Exception e) {
        System.out.println("Draft01 "+e);
        System.exit(1);
    }
}