fieldnames(class_obj) vs properties(class_obj) ?

27 次查看(过去 30 天)
Ian
Ian 2026-1-30,20:09
编辑: Matt J 2026-1-31,15:30
Question re using fieldnames(obj) vs properties(obj) on Matlab class objects:
In earlier versions of matlab, fieldnames(obj) only worked on struct objects; one had to use properties(obj) to get the names of properties in a Matlab class object. (IIRC, as late as 2015x)
It appears that fieldnames(obj) now works for class objects as well. (this on R2024b*, tho IIRC it worked in 24a as well, possibly earlier)
However, R2025b documentation doesn't mention using fieldnames(...) for class objects, and lists properties(obj) as the function to get class object property names. Is this an undocumented feature that may go away, or is this intended behaviour going forward for fieldnames(...) , and documentation just hasn't kept up?
I note that fieldnames(...) cannot be stepped into with the debugger, so am guessing it must be implemented in underlying Java of mex code.
Also of note is that fieldnames(...) has an optional parameter of '-full' which apparently returns inheritance information on java and com objects (though apparently not on inheritance of Matlab parent/child classes).
* (Yes, I know it's 2026, not 2024...just current w/ linux version available on university's HPCC)

回答(1 个)

Rik
Rik about 3 hours 前
Did you check the release notes? If they don't mention this as a dev direction, you should consider this undocumented.
The underlying reason is that objects in Matlab share a lot of features with structs. You can call struct on an object to reveal most (usually all) properties, even if they are hidden:
struct(figure);
Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should thus be avoided. Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for more information.
You should remember to use properties for objects, as a class may have a custom implementation to return a sanitized list.
  1 个评论
Matt J
Matt J about 1 hour 前
编辑:Matt J 38 minutes 前
The underlying reason is that objects in Matlab share a lot of features with structs. You can call struct on an object to reveal most (usually all) properties, even if they are hidden:
That doesn't quite explain it for me. Simple tests show that fieldnames(obj) is not equivalent to fieldnames(struct(obj)). As demonstrated below, fieldnames(obj) does not reveal hidden or protected properties.
fieldnames(myclass)
ans =
1×1 cell array
{'c'}
properties(myclass)
Properties for class myclass:
c
classdef myclass
properties (GetAccess=protected)
a,b
end
properties
c
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by