如您所知,在编写 Android 应用程序时传递类类型很重要。 一个简单的示例是使用 Intent。
Intent i = new Intent(this, MyActivity.class);
所以在某些情况下,如果我可以将类类型信息保存到文件中供以后使用,例如,在重新启动后使用,它会很有用。
void saveClassTypeInfo(Class<?> classType, String filename) {
String str = null;
// Some job with classType
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
}
}
如果我能像上面那样以某种方式保存,那么我将来就能把它放回这样的 Intent 中。
Intent i = new Intent(this, restoredClassInfoFromFile);
我怎样才能得到这样的工作?因为Class<?>
不是一个对象,我根本不知道从哪里开始。
[编辑] .class 也是一个对象,所以我们可以像保存对象一样保存它。
最佳答案
这可以使用 ObjectOutputStream
这里 SaveState
是您的自定义类
public static void saveData(SaveState instance){
ObjectOutput out;
try {
File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(instance);
out.close();
} catch (Exception e) {e.printStackTrace();}
}
public static SaveState loadData(){
ObjectInput in;
SaveState ss=null;
try {
in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));
ss=(SaveState) in.readObject();
in.close();
} catch (Exception e) {e.printStackTrace();}
return ss;
}
关于java - 将类类型信息保存到文件以备后用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180144/