Suppose you have this class:
public class A
{
private int number;
public setNumber(int n){
number = n;
}
}
I’d like the method setNumber could be called only by objects of a specific class.
Does it make sense? I know it is not possible, is it? Which are the design alternatives?
Some well known design pattern?
Sorry for the silly question, but I’m a bit rusty in OO design.
EDIT: I should be more clear. Sorry.
I know setNumber can be invoked only by objects of class A. I’d like that only objects of a specific class (having a reference to class A objects), could call
classAObj.setNumber(n);
Let’s say you want
setNumberto be only called by classAllowedSetNumber. One possible solution is to mandate that you pass an instance ofAllowedsetNumberas a parameter, e.g.So then the question becomes, how can I stop anyone from creating an
AllowedSetNumberinstance. This is quite a bit easier to nail down – you can do that with object factories. Making the constructor ofAllowedSetNumberpackage private, or even private with a factory method.Another alternative, that doesn’t require changing the method signature, is to have a thread-local security context in the same vein as the java SecurityManager. This works by analysing stack traces when an object requests permission, and so the calling code can be authenticated, and then authorized according to the security policy.
See
java.security.PrivilegedAction<T>