How to prevent public methods from being called from specific classes

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.

Leave a Comment