matlab - 防止序列化

标签 matlab serialization

我有一个 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.

但这并不令人满意,因为我不想依赖未记录的功能,而且我当然不想强制用户这样做。

如何有效地抛出错误,防止用户尝试从我的类中序列化对象?


根据要求,重现情况的最小示例:

% 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 

最佳答案

就个人而言,我更喜欢将所有属性标记为Transient,并让对象有效地具有作为保存/加载结果的无效状态。阻止 MATLAB 保存您的数据非常困难,而且您的解决方法可能会严重干扰用户的工作流程。

关于matlab - 防止序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475363/

相关文章:

string - 使用 sscanf 扫描日期

javascript - 有没有一种方法可以指定在序列化时将对象的哪些数据传递给序列化程序?

c# - 将 JSON 中的嵌套对象反序列化为特定类型

image - 将绘图保存到 matlab : difference between saveas and print 中的图像文件中

matlab - 在 Matlab 中可视化环形曲面

matlab - 如何在matlab中使用 'menu'函数携带逻辑函数?

java - Spring Boot 忽略@JsonDeserialize 和@JsonSerialize

javascript - 协议(protocol) JSON (PSON) 与 Protocol Buffer

java - Jersey/Jackson - 类对象序列化

c++ - 关于 MATLAB 中 MEX 函数逻辑输出的问题