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

3 visualizaciones (últimos 30 días)
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?

Respuestas (2)

Matt J
Matt J el 6 de Abr. de 2022
Editada: Matt J el 6 de Abr. de 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

Steven Lord
Steven Lord el 7 de Abr. de 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)
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'.

Categorías

Más información sobre Class File Organization en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by