Empty array of class objects from string name of class
古いコメントを表示
If I have a class called SomeClass, I can create an empty array of SomeClass using:
arr = SomeClass.empty
Is there a way to create an empty array if I only have the character string "SomeClass".
5 件のコメント
Image Analyst
2018 年 8 月 17 日
編集済み: Image Analyst
2018 年 8 月 17 日
I think you mean
str = "SomeClass"; % Here is the character string.
eval(sprintf('arr = %s.empty', str)); % Put into command string and pass to eval()
SK
2018 年 8 月 17 日
Although slightly different from the usual approach, this will have almost all of the same disadvantages as the usual dynamic variable names that some beginners like to use to force themselves into writing slow, complex, buggy code:
回答 (3 件)
Guillaume
2018 年 8 月 18 日
"Those familiar with Matlab will know that this will not work"
This.elements(end+1) = obj;
Indeed, but the semantically equivalent
This.element = [This.element, obj];
will. No need to test for emptiness.
Image Analyst
2018 年 8 月 17 日
0 投票
Doing this - making variables named from strings - is a bad idea. I mean, just how would you refer to that variable later? How would you use it if you don't know the variable name before run-time? See this link
2 件のコメント
Steven Lord
2018 年 8 月 17 日
It's extremely easy to come up with a piece of text that is not a valid class name but if used with Image Analyst's suggestion would do various nasty things. I'm not going to post one because I don't want people to get angry if they closed their MATLAB session by running the example.
If you must use this approach to run code from your users, make absolutely sure to sanitize your inputs. Use meta.class.fromName to validate that the class name you've been given is an actual class. Here's one that does not exist:
name = 'thisClassDoesNotExist';
if isempty(meta.class.fromName(name))
fprintf('The class %s does not exist!\n', name);
else
fprintf('Class name %s exists, you may create an empty.\n', name);
end
Here's one that does.
name = 'table';
if isempty(meta.class.fromName(name))
fprintf('The class %s does not exist!\n', name);
else
fprintf('Class name %s exists, you may create an empty.\n', name);
end
SK
2018 年 8 月 18 日
カテゴリ
ヘルプ センター および File Exchange で Data Type Identification についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!