Selective access to your class or methods to execute
Suppose you want to put restrictions to certain classes or methods in classes to access your method, then we generally use AccessSpecifier to restrict the access, but what if you want to restrict the access to some classes in the same package even. Though it may be weird use case but suppose you still want your methods visible to public but still you want to restrict.
Then how will you do that?
First list all the classes & methods in some properties file or file from where you can read all those names to check with.
Then put the below kind of utility class to determine the names of the callers & on that basis you can decide if you need to restrict. An example is given below where Class3 is not allowed to access the method in Class1 directly.
Then how will you do that?
First list all the classes & methods in some properties file or file from where you can read all those names to check with.
Then put the below kind of utility class to determine the names of the callers & on that basis you can decide if you need to restrict. An example is given below where Class3 is not allowed to access the method in Class1 directly.
One can use getCallingClassesFast() to get the names of classes in that calling hierarchy & it is supposed to give results faster, but still please study about SecurityManager before deciding on any implementation to confirm the required performance.
Now below I created 3 classes in the same package to show the usage -
Now below I created 3 classes in the same package to show the usage -
If you are using Java9, & want to have above kind of behaviour implemented then can look for StackWalker introduced there.
Go through its docs & tutorials like - https://www.baeldung.com/java-9-stackwalking-api
In case you need the sample, please let me know & I will paste that here.
Go through its docs & tutorials like - https://www.baeldung.com/java-9-stackwalking-api
In case you need the sample, please let me know & I will paste that here.