竟然有高手 2021-02-07 22:27 采纳率: 0%
浏览 22

java对象序列化问题

public class A implements Serializable{
    public interface a {
        void b();
    }
}



*************

public class Main {
    public static void main(String[] args) {
        List<A.a> As = new ArrayList<>();
        As.add(new A.a() {
            @Override
            public void b() {

            }
        });
        Tools.Serilizable(As,"1");
        Tools.DisSerilizable("1");
    }
}


**************


public class Tools {
    public static List<Item> ListMerge(List<Item> arg1,List<Item> arg2) {
        for (int i = 0;i < arg2.size();i++) {
            arg1.add(arg2.get(i));
        }
        return arg1;
    }

    public static void Serilizable(List<A.a> actions,String TAG) {
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream(TAG+".txt"));
            out.writeObject(actions);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<A.a> DisSerilizable(String TAG) {
        ObjectInputStream in = null;
        try {
            in = new ObjectInputStream(new FileInputStream(TAG+".txt"));
            return  (List<A.a>) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            Serilizable(new ArrayList<A.a>(),TAG);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }
}

使用A类下的接口a作为类型的List<>,在(List<A.a>)不为空时会序列化失败的问题

 

希望大佬能够帮我解惑,感激不尽

  • 写回答

1条回答 默认 最新

  • IT-猕猴桃 2021-02-08 10:17
    关注

    我看出来两个问题:

    1)你的A类的内部接口a没有继承Serializable,这导致你通过匿名类实现的a的对象不能进行实例化,所以总出问题。

    2)ListMerge方法的泛型使用错误

    评论

报告相同问题?

悬赏问题

  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
  • ¥15 ADS时域 连续相位观察方法
  • ¥15 Opencv配置出错
  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused