Example - Restricting callers

In this section we develop a sample library with two methods. The hello() method prints hello to the standard output. The callMe() method accepts a Runnable as an argument and runs it. The first method however is restricted. It executes only if the caller is purely outside of the library. It throws an IllegalCallerException if the caller obtained the control in a way that the library was calling out, presumably via the second method invoking the passed Runnable. The implementation of the API is simple:

 package packt.java9.deep.stackwalker.myrestrictivelibrary; public class RestrictedAPI { public void hello(){ CheckEligibility.itIsNotCallBack(); System.out.println("hello"); } public void callMe(Runnable cb){ ...

Get Java 9: Building Robust Modular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.