java如何保存类,如何在Java中将静态类保存到文件中?(How to save a static class to file in Java?)...

这篇博客介绍了如何使用Java实现静态字段的单独保存和加载,通过定义`saveField`和`readField`方法,将静态变量写入和读取到文件中,实现了静态数据的持久化。这种方法适用于需要保存类静态状态的场景。
摘要由CSDN通过智能技术生成

As far as Im aware you cant do it like that. But you could write the static fields individually rather than the whole class in one go.

eg.

public class MyClass() {

private static String staticField1;

private static String staticField2;

static {

load();

}

private static void saveField(String fieldName, Object fieldValue) throws IOException {

FileOutputStream fos = new FileOutputStream(new File("MyClass-" + fieldName + ".dat"));

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(fieldValue);

oos.close();

}

private static Object readField(String fieldName) throws IOException {

FileInputStream fis = new FileInputStream(new File("MyClass-" + fieldName + ".dat"));

ObjectInputStream ois = new ObjectInputStream(fis);

Object value = ois.readObject();

ois.close();

return value;

}

private static void save() throws IOException {

saveField("staticField1", staticField1);

saveField("staticField2", staticField2);

}

private static void load() throws IOException {

staticField1 = (String)readField("staticField1");

staticField2 = (String)readField("staticField2");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值