Java Transient关键字与示例
时间:2020-02-23 14:35:16 来源:igfitidea点击:
Transient(瞬时)变量是在序列化期间未序列化的变量。
当我们将其进行反序列化时,我们将获得这些变量的默认值。
让我们说你有国家级,你不想序列化人口属性随着时间的变化,因此我们可以将群体属性声明为暂行,它不会再序列化。
Transient关键字示例:
创建一个名为country.java的类:
package org.igi.theitroad; import java.io.Serializable; public class Country implements Serializable { String name; transient long population; public Country() { super(); } public Country(String name, long population) { super(); this.name = name; this.population = population; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getPopulation() { return population; } public void setPopulation(long population) { this.population = population; } }
创建SerializationMain.java如下:
package org.igi.theitroad; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializeMain { /** * @author igi Mandliya */ public static void main(String[] args) { Country Netherlands = new Country(); Netherlands.setName("Netherlands"); Netherlands.setPopulation(100000); try { FileOutputStream fileOut = new FileOutputStream("country.ser"); ObjectOutputStream outStream = new ObjectOutputStream(fileOut); outStream.writeObject(Netherlands); outStream.close(); fileOut.close(); }catch(IOException i) { i.printStackTrace(); } System.out.println("serialized"); } }
运行上面的程序时,我们将得到以下输出:
serialized
现在创建一个名为deserializemain.java的被归类为下面的:
package org.igi.theitroad; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeserializeMain { /** * @author igi Mandliya */ public static void main(String[] args) { Country Netherlands = null; try { FileInputStream fileIn =new FileInputStream("country.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Netherlands = (Country) in.readObject(); in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println("Country class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Country..."); System.out.println("Country Name : " + Netherlands.getName()); System.out.println("Population : " + Netherlands.getPopulation()); } }
运行上面的程序时,我们将得到以下输出:
Deserialized Country... Country Name : Netherlands Population : 0
正如我们可以在上面的例子中看到的,我们已将人口声明为初始,因此在反序列化之后,其值为0(长期默认值)