需求:
给你任意的一个对象,将成员变量给保存到文件中。
public static void save(Object o) {
try ( //创建传输文件对象,并且再之前的基础上继续传输数据
PrintStream ps = new PrintStream(new FileOutputStream("Path路径"),true)
){
//获取传入类的Class对象
Class<?> c = o.getClass();
//通过class对象获取成员变量
Field[] frr = c.getDeclaredFields();
//获取类对象名字
ps.println("=========="+c.getSimpleName()+"==============");
//遍历获取到的成员变量数组
for (Field field : frr) {
// 设置一切可见
field.setAccessible(true);
//存储变量到文件中
ps.println(field.getName()+"===>"+field.get(o));
}
} catch (Exception e) {
e.printStackTrace();
}
}
创建一个Hero类
public class Hero {
//成员变量
private String name ;// 英雄名称
private int hp;// 英雄HP
private int mp;// 英雄MP
private int attack;// 英雄攻击力
private int defense;// 英雄防御
//构造方法
public Hero() {
}
public Hero(String name, int hp, int mp, int attack, int defense) {
this.name = name;
this.hp = hp;
this.mp = mp;
this.attack = attack;
this.defense = defense;
}
}