Any way to get the "current" class

조회 수: 23 (최근 30일)
Joan Puig
Joan Puig 2013년 5월 29일
Hi,
I am writing some object oriented code (with classdef), and it would be convenient for me to have a function like this:
meta.class.getCurrent()
Where it returns the metadata of the class in which it is called. In the event that the function is called from some other place (script or simple function) it should error
Is there a way to get that?
Thanks, Joan
  댓글 수: 1
Joan Puig
Joan Puig 2013년 5월 30일
One of the goal is to be able to write error messages that include the class name on it. At the same time, to make the code as easy to maintain as possible, I don't want to hardcode the class name.

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

채택된 답변

per isakson
per isakson 2013년 6월 6일
This might be a start. (TODO: not a class, class in package, function in package.)
>> MyTestClass.Update
Class_name: MyTestClass
Method_name: Update
where
classdef MyTestClass < handle
methods ( Static )
function Update()
[ cls, method ] = current_class();
fprintf( 'Class_name: %s\nMethod_name: %s\n', cls.Name, method )
end
end
end
and
function [ cls, str ] = current_class( )
%
% See also: mfilename
dbk = dbstack( 1, '-completenames' );
if isempty( dbk )
str = 'base';
else
str = dbk(1).name;
end
cac = regexp( str, '\.', 'split' );
switch numel( cac )
case 1
case 2
cls = meta.class.fromName( cac{1} );
str = cac{2};
case 3
otherwise
end
end
  댓글 수: 1
Joan Puig
Joan Puig 2013년 6월 6일
Yes, this sounds like it should work.
Thanks!

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

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2013년 5월 29일
편집: Sean de Wolski 2013년 5월 29일
Not sure I totally understand what you want. You have a class, C, and you pass an object, obj, of class C into some function, foo, via one of its methods or some other function and you want to be able to retreive the metadata of the obj or of class C? If the object is available, use:
?obj
If that is not the case, could you please clarify. You could have your function to a simple:
isa(obj,'C')
as well or instead...
  댓글 수: 1
Joan Puig
Joan Puig 2013년 5월 30일
Using the metaclass(object) will get me a step closer, but in the static context I do not have access to an object to be able to pass it in.

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

카테고리

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