一道关于java序列化的问题,看大家知多少————

问题先放在这里,稍后我会做出解答

已知类有Test和Test2,问两次主程序的输出结果是多少(SerializeUtil只是序列化的工具类)

类Test

public class Test implements Serializable{
private static final long serialVersionUID = 1L;
private int num;
private transient String str; public Test(){
this.num = 0xFFFF;
this.str = "string";
} public Test(int num, String str) {
this.num = num;
this.str = str;
} @Override
public String toString() {
return num + ","+str;
}
}

类Test2

public class Test2 implements Externalizable,Serializable{
private static final long serialVersionUID = 1L;
private int num;
private transient String str; public Test2() {
this.num = 0xFFFF;
this.str = "hello";
} public Test2(int num, String str) {
this.num = num;
this.str = str;
} @Override
public void writeExternal(ObjectOutput out) throws IOException {
out.write(num);
} @Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.num = in.read();
} @Override
public String toString() {
return num + ","+str;
}
}

两个主程序:

    public static void main(String[] args) {
Test test = new Test();
File file = new File("d:/test.bin");
SerializeUtil.writeObject(file,test); Test test2 = (Test) SerializeUtil.readObject(file);
System.out.println(test);
System.out.println(test2);
}
    public static void main(String[] args) {
Test2 test2 = new Test2();
File file = new File("d:/test2.bin"); SerializeUtil.writeObject(file,test2);
Test2 t = (Test2) SerializeUtil.readObject(file); System.out.println(test2);
System.out.println(t);
}

附SerializeUtil的代码,可无视——

 public class SerializeUtil {

     public static void writeObject(File file,Object object){
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {}
}
}
} public static Object readObject(File file){
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
return objectInputStream.readObject();
}catch (ClassNotFoundException|IOException e){
e.printStackTrace();
}finally {
if(fileInputStream!=null){
try {
fileInputStream.close();
} catch (IOException e) {}
}
}
return null;
} }

序列化工具类

答案如下:

/*
第一个主程序:
65535,string
65535,null
第二个主程序:
65535,hello
255,hello
*/

答案

上一篇:python学习--python 连接SQLServer数据库(两种方法)


下一篇:史上最全的 jmeter 获取 jdbc 数据使用的4种方法——(软件测试Python自动化)