How to create an object using class name

조회 수: 70 (최근 30일)
Sylvain
Sylvain 2020년 2월 18일
댓글: Sylvain 2020년 2월 21일
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

채택된 답변

Matt J
Matt J 2020년 2월 18일
function newObj = createNewObject(obj)
newObj = feval( class(obj) );
end
  댓글 수: 3
Sylvain
Sylvain 2020년 2월 21일
Thank you, very instructive

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Sky Sartorius
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

Image Analyst
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
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 CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by