How would I prevent access to classes that shouldn't be publicly available in my toolkit?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (2)
Matt J
am 6 Apr. 2022
Bearbeitet: Matt J
am 6 Apr. 2022
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
0 Kommentare
Steven Lord
am 7 Apr. 2022
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)
% These don't work
try
z = class1690285_private(7);
catch ME
fprintf("The error was: %s\n", ME.message)
end
try
z = class1690285_private.makeOne(7);
catch ME
fprintf("The error was: %s\n", ME.message)
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!