Friend in Java

February 19th, 2008

Sometimes, you want to change behaviour of a method, depending on who the caller is. An example might be to throw an exception if the caller is a class you don't know. You want to make the method protected, but for some reason, you can't put all the callers in the same package as the callee. In C++, you have the concept of 'friend', where a callee can define which callers are allowed. Or so it exists in my memory, but that doesn't matter. To achieve the same thing in Java, you can inspect the stacktrace: public boolean isFriend() { new Exception().getStackTrace()[2].getClassName().startsWith(MY_PACKAGE_NAME); } And use it as follows:
public void something() { if (!isFriend()) { throw new NotFriendException(); else { // do nifty stuff here } }
Now, while this works, I have a sneaky suspicion that this isn't the most performant solution: creating a stacktrace is said to be an expensive operation. But it's useful once in a while.

2 Responses to “Friend in Java”

  1. Mike Kaufman Says:
    For info, from Java SE 5 onwards java.lang.Thread has a getStackTrace() method through which you can get the stack trace without having to construct an exception (i.e. you can use Thread.currentThread.getStackTrace).
  2. Tom Klaasen Says:
    @Mike: Thanks for the tip. This code is copied from a Java 1.4 project. I didn't spend time to update it.

Leave a Reply