How to prevent public methods from being called from specific classes

Bagmita picture Bagmita · Mar 30, 2011 · Viewed 8.9k times · Source

I have an existing class into which I want to add a method. But I want the method to be called only from a specific method from a specific class. Is there any way that I can prevent that call from other classes/methods?

For example, I have an existing class A

public final class A
{
    //other stuff available for all classes/methods

    //I want to add a method that does its job only if called from a specific method of a class, for example:

    public void method()
    {
        //proceed if called from Class B.anotherMethod() else throw Exception
    }
}

One way of doing this is getting the StackTrace inside the method() and then confirming the parent method?

What I am looking for is a solution that is more clean and advisable solution like a pattern or something.

Answer

Stephen C picture Stephen C · Mar 30, 2011

To be honest, you have painted yourself into a corner here.

If classes A and B are not related and not members of the same package, then visibility won't solve the problem. (And even if it did, reflection can be used to subvert the visibility rules.)

Static code analysis won't solve the problem if the code can use reflection to call the method.

Passing and checking B.this as an extra parameter to A.method(...) doesn't help because some other class C could pass a B instance.

This leaves only the stacktrace approach1... or giving up and relying on the good sense of the programmer2 not to call methods that they shouldn't.


The ideal solution is to revisit the design and/or coding decisions that got you into this mess.


1 - See other answers for examples that use annotations, a security manager, etc to conceal the stacktrace stuff from the application programmer. But note that under the hood you are adding probably hundreds, possibly thousands of instructions overhead per method call.

2 - Do not underestimate the programmer's good sense. Most programmers, when they see advice not to call some method, are likely to follow that advice.