zoukankan      html  css  js  c++  java
  • Externalizable的使用方法

    package com.itbuluoge.object;
    
    import java.io.Externalizable;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInput;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutput;
    import java.io.ObjectOutputStream;
    
     class Moon implements Externalizable{
    
    	public Moon()
    	{
    		System.out.println("moon");
    	}
    	public void readExternal(ObjectInput arg0) throws IOException,
    			ClassNotFoundException {
    		// TODO Auto-generated method stub
    		System.out.println("reading moon!");
    	}
    
    	public void writeExternal(ObjectOutput arg0) throws IOException {
    		// TODO Auto-generated method stub
    		System.out.println("writing moon!");
    	}
    
    }
    class Sun implements Externalizable
    {
    	Sun()
    	{
    		System.out.println("sun");
    	}
    	public void readExternal(ObjectInput in) throws IOException,
    			ClassNotFoundException {
    		// TODO Auto-generated method stub
    		
    	}
    
    	public void writeExternal(ObjectOutput out) throws IOException {
    		// TODO Auto-generated method stub
    		
    	}
    	
    }
    
    public class Stars
    {
    	public static void main(String[] args) throws Exception, IOException
    	{
    		Moon moon=new Moon();
    		Sun sun=new Sun();
    		
    		ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("star.out"));
    		o.writeObject(moon);
    		o.writeObject(sun);
    		o.close();
    		
    		ObjectInputStream in=new ObjectInputStream(new FileInputStream("star.out"));
    		moon=(Moon)in.readObject();
    		sun=(Sun)in.readObject();
    		in.close();
    		
    	}
    }



    我们能够看到输出结果



    我们对moon的写和读序列化都没有问题,可是对sun的写没有问题,可是在读出的时候。抛出异常,由于实现了Externalizable接口的类,会调用构造函数,而sun的构造函数是私有的。无法訪问,从而导致抛出异常。

  • 相关阅读:
    leetcode:Valid Parentheses(有效括号匹配)
    leetcode:Remove Nth Node From End of List (移除从尾部数的第N个节点)
    leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)
    leetcode:4Sums(四个数相加的和)
    leetcode:3Sum Closest
    leetcode:3Sum (三个数的和)
    leetcode:Longest Common Prefix(取最长字符串前缀)
    php数据访问
    PHP 基础知识测试题
    面相对象设计模式
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/7354366.html
Copyright © 2011-2022 走看看