【问题标题】:How to Deserialize the current object如何反序列化当前对象
【发布时间】:2020-03-28 18:30:18
【问题描述】:

我创建了一个bankStatement 程序,其中有两个类,例如MainFinancialManager。在这个程序中,我可以提取、存款和查看当前帐户余额。 这是我的 FinancialManager 课程

import java.io.*;
import java.util.Vector;

public class FinancialManager implements Serializable {
    private double balance1;
    private Vector<String> statement1;
    public FinancialManager(){
        balance1=0;
        statement1 = new Vector<String>();
    }
    public void deposit(double value){
        balance1 = balance1+value;
        String st = "Deposit  "+String.valueOf(value);
        statement1.add(st);
    }
    public void withdraw(double value){
        if(value<balance1){
            balance1 = balance1 - value;
            String st = "Withdraw "+String.valueOf(value);
            statement1.add(st);
        }else{
            String st = "Withdraw 0.0";
            statement1.add(st);
        }
    }
    public String balance(){
        return String.valueOf(balance1);
    }
    public void statement(){
        String[] array = statement1.toArray(new String[statement1.size()]);
        for(int i=0;i<array.length;i++){
            System.out.println(array[i]);
        }
    }

    public void save(String fileName) throws IOException {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(fileName))) {
            // write "this" - the current object - to the file
            objectOutputStream.writeObject(this);
        }
    }

}

我的主课在下面

public class Main {
    public static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        FinancialManager fm = new FinancialManager();
        fm.deposit(25.00);
        fm.withdraw(12.00);
        fm.deposit(10.00);
        fm.deposit(5.00);
        fm.withdraw(8.00);
        System.out.println("The current balance is "+fm.balance());
        fm.statement();
        fm.save("text.txt");

        FinancialManager anotherfm = new FinancialManager();

    }
}

我可以使用这个关键字在我的 FinancialManager 中创建 Serialization 方法。但我不知道如何创建 Deserialization 方法。how我可以这样做吗? 请帮我解决这个问题。FinancialManager 类中的方法应该是这样的。

public void load(String filename){
   //Write your code here
}

需要像这样在Main类中使用这个方法

FinancialManager anotherFM = new FinancialManager(); 
anotherFM.load(laccountl");
anotherFM.statement();

【问题讨论】:

    标签: java file serialization stream deserialization


    【解决方案1】:

    反序列化创建对象。该对象不应该已经存在。因此make in static,和创建方法一样(如List.of)。

    但是,Secure Coding Guidelines for Java SE 说:

    注意:不可信数据的反序列化本质上是危险的,并且 应该避免。

    我不会碰 Java 序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-26
      • 2017-03-16
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2017-03-06
      相关资源
      最近更新 更多