8
기본 클래스의 소스 코드를 제어 할 수 없다면 어떻게 하위 클래스에서 표준 직렬화를 사용할 수 있습니까?표준 직렬화에서 직렬화 할 수없는 기본 클래스를 직렬화하는 방법은 무엇입니까?
//에 a.jar
class A {
int a;
}
// b.JAR가
class B
extends A
implements Serializable {
int b;
}
public class HelloWorldApp {
public static void main(String[] args)
throws Exception {
B b = new B();
b.a = 10;
b.b = 20;
ByteArrayOutputStream buf = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(buf);
out.writeObject(b);
out.close();
byte[] bytes = buf.toByteArray();
ByteArrayInputStream _in = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(_in);
B x = (B) in.readObject();
System.out.println(x.a);
System.out.println(x.b);
}
}
출력 : B 직렬화 비록이 예에서
는 필드a
는 전혀 없다 직렬화 :
0
20
그런 다음 모든 비어 있지 않은 생성자 전용 클래스에 Serializble 인터페이스를 표시해야합니까? –
아니요, 필요하지 않습니다. 다음 코드를 갖습니다 : public class B extends A extends Externalizable {public void writeExternal (ObjectOutput out) {out.write (a); out.write (b); } public void readExternals (ObjectInput in) {a = in.readInt(); b = in.readInt(); }} – alexey28
-1. 당신의 마음을 확인하십시오. 할 수 있거나 할 수 없습니다. 동시에 둘 다 아닙니다. – EJP