Java是一種面向?qū)ο蟮木幊陶Z言,序列化是對Java對象進(jìn)行編碼,以便在網(wǎng)絡(luò)上傳輸或永久存儲。
Java序列化可以將Java對象轉(zhuǎn)換成字節(jié)序列,以便存儲在本地文件系統(tǒng)或通過網(wǎng)絡(luò)傳輸。Java序列化需要使用ObjectOutputStream類輸出字節(jié)流,并使用ObjectInputStream讀取字節(jié)流。序列化使得Java對象能夠以一種可傳輸、可存儲的格式進(jìn)行存儲和傳輸,因此在Java開發(fā)中非常有用。
//示例Java對象 public class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } //序列化示例 Person person = new Person("張三", 20); try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser")); oos.writeObject(person); oos.close(); } catch (IOException e) { e.printStackTrace(); } //反序列化示例 try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser")); Person p = (Person) ois.readObject(); System.out.println("姓名:" + p.getName() + ",年齡:" + p.getAge()); ois.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
Hessian是一種基于二進(jìn)制協(xié)議的RPC協(xié)議,能夠?qū)ava對象通過網(wǎng)絡(luò)傳輸。相比于Java序列化,Hessian的傳輸效率更高,且支持多種語言的客戶端訪問。
//示例代碼 public interface HelloService { String sayHello(String name); } public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name; } } public class HessianServer { public static void main(String[] args) throws IOException { HelloService helloService = new HelloServiceImpl(); HessianServlet servlet = new HessianServlet(); servlet.setServant(helloService); Endpoint.publish("http://localhost:8080/hessian", servlet); } } public class HessianClient { public static void main(String[] args) throws MalformedURLException { String url = "http://localhost:8080/hessian"; HessianProxyFactory factory = new HessianProxyFactory(); HelloService helloService = (HelloService) factory.create(HelloService.class, url); String result = helloService.sayHello("張三"); System.out.println(result); } }
Java序列化和Hessian都是將Java對象轉(zhuǎn)為二進(jìn)制流進(jìn)行傳輸,但Hessian相比于Java序列化更加高效,并且支持跨語言訪問。在實(shí)際開發(fā)中,應(yīng)根據(jù)具體需求選擇合適的序列化方式。