利用Serializable可以实现对象的数据装入,但是必须在外部调用objectInputStream进行
class CTest implements Serializable{
}
class CApp{
pubic static void main throws Exception(){
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("abc.dat"));
CTest tst=ois.read();
ois.close();
}
这很麻烦,我想写一个基类,使得继承类只用Constructor(String strPath)就可以自生从文件完成数据装入public class CStorable implements Serializable{
private static final long serialVersionUID = -4470165884594329153L; public static CStorable loadFromFile(File fle){
try{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(fle));
CStorable sta=(CStorable) ois.readObject();
ois.close();
return sta;
}catch (Exception e){
e.printStackTrace(System.out);
return null;
}
}
public static CStorable loadFromFile(String strPath){
return loadFromFile(new File(strPath));
} public CStorable(String strPath){this=loadFromFile(strPath);} //这里是错误的这个使用loadFromFile的静态方法没什么问题,例如CStorable sta=CStroable.loadFromFile("abc.dat"),ok但是如果使用构造发直接创建就报错CStorable sta=new CStorable("abc.dat");err
这个我可以理解,this=loadFromFile(strPath),等于动态类了,因该是报错的。那么还有其他解决办法吗?
class CTest implements Serializable{
}
class CApp{
pubic static void main throws Exception(){
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("abc.dat"));
CTest tst=ois.read();
ois.close();
}
这很麻烦,我想写一个基类,使得继承类只用Constructor(String strPath)就可以自生从文件完成数据装入public class CStorable implements Serializable{
private static final long serialVersionUID = -4470165884594329153L; public static CStorable loadFromFile(File fle){
try{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(fle));
CStorable sta=(CStorable) ois.readObject();
ois.close();
return sta;
}catch (Exception e){
e.printStackTrace(System.out);
return null;
}
}
public static CStorable loadFromFile(String strPath){
return loadFromFile(new File(strPath));
} public CStorable(String strPath){this=loadFromFile(strPath);} //这里是错误的这个使用loadFromFile的静态方法没什么问题,例如CStorable sta=CStroable.loadFromFile("abc.dat"),ok但是如果使用构造发直接创建就报错CStorable sta=new CStorable("abc.dat");err
这个我可以理解,this=loadFromFile(strPath),等于动态类了,因该是报错的。那么还有其他解决办法吗?
已经是静态方法了,还在构造函数里写啥?在其他类里直接调用不就可以了
class CApp{
pubic static void main throws Exception(){
CStorable cs = CStroable.loadFromFile("abc.dat");
}
}