필터 지우기
필터 지우기

How would I prevent access to classes that shouldn't be publicly available in my toolkit?

조회 수: 4 (최근 30일)
I have a toolkit where I would like to provide some public functions and classes to the user (a public API). There are also many functions and classes that the user doesn't need access to. For the functions, I can create a folder named private and then put the public functions and classes one level above. This makes it where the public functions and classes can still call these private functions without exposing them to the user (i.e., the user can't call them from the command window or outside the folder). However, classes can't go inside private folders. How would I go about preventing access like I did with the private functions for my classes?

답변 (2개)

Matt J
Matt J 2022년 4월 6일
편집: Matt J 2022년 4월 6일
You cannot truly hide the class, but you can have its constructor raise an error when someone tries to invoke it from outside your toolkit folder by doing something like below. Obviously also, you can make specific class methods private to the class using method attributes.
classdef myclass
methods
function obj=myclass
s=dbstack('-completenames');
pthCaller=fileparts(s(2).file);
pthPrivate=fileparts(which('myclass'));
if ~strcmp(pthCaller,pthPrivate)
error 'Class is private'
end
end
end
end

Steven Lord
Steven Lord 2022년 4월 7일
The way I'd probably do this is to make the class constructor for the "private" classes have Access='protected' (so only accessible in the class and its subclasses) and give the private classes a Static method that can call the protected constructor. Make that Static method only allow Access to a fixed set of classes or functions.
See the attached two classes.
% This works
y = class1690285_public(5); % invokes the Static method in class1690285_private
% which invokes the constructor of class1690285_private
getDataFromPrivate(y)
ans = 25
% These don't work
try
z = class1690285_private(7);
catch ME
fprintf("The error was: %s\n", ME.message)
end
The error was: Cannot access method 'class1690285_private' in class 'class1690285_private'.
try
z = class1690285_private.makeOne(7);
catch ME
fprintf("The error was: %s\n", ME.message)
end
The error was: Cannot access method 'makeOne' in class 'class1690285_private'.

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by