2013-03-18 86 views
2

我有一個Matlab類,實現序列化和反序列化會很痛苦,而且不需要。 因此,我已經超負荷saveobj如下:防止序列化

function sobj = saveobj(self) 
     sojb = []; 
     error(['atmlab:' mfilename ':nostoring'], ... 
      ['You tried to store %s %s. Loading is impossible, ' ... 
      'therefore I refuse to store. Sorry.'], ... 
      class(self), self.name); 
    end 

不幸的是,當我測試,Matlab的嘗試是有益的,變成警告到錯誤(兩次出於某種原因):

>> save('/tmp/test.mat', 'X') 
Warning: While saving an object of class 'SatDataset': 
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry. 
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.) 
Warning: While saving an object of class 'SatDataset': 
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry. 
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.) 

我可以使用undocumented feature打開警告插入錯誤:

>> warning error atmlab:SatDataset:nostoring 
>> save('/tmp/test.mat', 'X') 
Error using save 
While saving an object of class 'SatDataset': 
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry. 

Unexpected error status flag encountered. Resetting to proper state. 

但是,這並不理想,因爲我不想要依靠UNDOC並且我肯定不想強迫用戶這樣做。

我該如何有效地拋出一個錯誤,防止用戶嘗試從我的班級串行化對象?


按要求,最低例子重現情況:

% in TestClass.m 
classdef TestClass < handle 
    methods 
     function sobj = saveobj(self) 
      sojb = []; 
      error('Unable to store %s objects', class(self)); 
     end 
    end 
end 

% on the interactive prompt: 

>> t = TestClass(); 

>> save('/tmp/fubar.mat', 't'); 
Warning: While saving an object of class 'TestClass': 
Unable to store TestClass objects 
Warning: While saving an object of class 'TestClass': 
Unable to store TestClass objects 

回答

3

個人取代你的error()電話,我更喜歡將所有屬性標記爲Transient,並讓對象有效地具有無效狀態,即保存/加載的結果。防止MATLAB保存您的數據非常困難,您的解決方法可能會嚴重干擾用戶的工作流程。

-1

你的代碼實際上引發錯誤,你應該warning()

+0

不。我的代碼不會拋出錯誤,即使我調用'error',我的代碼也會拋出警告。 – gerrit 2013-03-18 12:30:10

+0

並且將呼叫更改爲警告並不能解決問題嗎? – 2013-03-18 17:08:57

+0

問題是我不能拋出錯誤,因爲Matlab會將錯誤更改爲警告。將其更改爲警告並不能解決無法拋出錯誤的問題。 – gerrit 2013-03-18 18:19:00

相關問題