How to create an object using class name
55 次查看(过去 30 天)
显示 更早的评论
In my function, I am getting the class name from an object to create a new one. What is the right syntax to creat the new Object ?
function newObj = createNewObject(obj)
className = class(obj);
newObj = className();
end
0 个评论
采纳的回答
更多回答(2 个)
Sky Sartorius
2020-2-18
A quick and dirty approach that will work in many cases is to use eval:
function new = createNewObjectOfThisClass(original)
new = eval([class(original) '.empty;']);
end
0 个评论
Image Analyst
2020-2-18
That won't work for all types of objects, like structures, other custom-designed classes, etc. I think your best bet is to just make a copy of the variable
function newObj = createNewObject(obj)
newObj = obj;
end
It will have the values of the input object, but more importantly, it will inherit all the fields, properties, and methods of your input class. As you can see you actually don't even need this function at all since it's just a wrapper than essentially does nothing. You could just simply do this
newObj = obj;
rather than this
newObj = createNewObject(obj)
1 个评论
Matt J
2020-2-18
编辑:Matt J
2020-2-18
I disagree. It's often necessary to call the constructor to instantiate a new, independent version of the original object. For example, if obj is an object of a handle class then
newObj = obj
does not give you an indepedent copy of obj. Just another handle to its property data.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!